Skip to content
Related Articles

Related Articles

Python – How to search for a string in text files?

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 25 Oct, 2022
Improve Article
Save Article

In this article, we are going to see how to search for a string in text files using Python


string = “GEEK FOR GEEKS”
Input: “FOR” 
Output: Yes, FOR is present in the given string.

Text File for demonstration:


Method 1:  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.


# 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'
        # 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(line))


string exists in file
line Number: 4

Method 2: 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.


with open(r'myfile.txt', 'r') as file:
        # read all content from a file using read()
        content =
        # check if string present or not
        if 'Line 8' in content:
            print('string exist')
            print('string does not exist')


string does not exist

Method 3: Search for a String in Text Files using enumerate()

We are just finding string is present in the file or not using the enumerate() in Python.


with open(r"myfile.txt", 'r') as f:
    for index, line in enumerate(f):
        # search string
        if 'Line 3y' in line:
            print('string found in a file')           
            # don't look for next lines
    print('string does not exist in a file')


string does not exist in a file

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!