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:

myfile.txt

Similar Reads

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....

Finding string in a text file using read()

...

Search for a String in Text Files using enumerate()

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....

Contact Us