Finding string in a text file using read()
we are going to search string line by line if the string is found then we will print that string and line number using the read() function.
Python3
with open (r 'myfile.txt' , 'r' ) as file : # read all content from a file using read() content = file .read() # check if string present or not if 'Line 8' in content: print ( 'string exist' ) else : print ( 'string does not exist' ) |
Output:
string does not exist
Python – How to search for a string in text files?
In this article, we are going to see how to search for a string in text files using Python
Example:
string = “GEEK FOR GEEKS”
Input: “FOR”
Output: Yes, FOR is present in the given string.
Text File for demonstration: