Finding the index of the string in the text file using readline()
In this method, we are using the readline() function, and checking with the find() function, this method returns -1 if the value is not found and if found it returns 0.
Python3
# string to search in file with open (r 'myfile.txt' , 'r' ) as fp: # read all lines using readline() lines = fp.readlines() for row in lines: # check if string present on a current line word = 'Line 3' #print(row.find(word)) # find() method returns -1 if the value is not found, # if found it returns index of the first occurrence of the substring if row.find(word) ! = - 1 : print ( 'string exists in file' ) print ( 'line Number:' , lines.index(row)) |
Output:
string exists in file line Number: 2
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:
Contact Us