Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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

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

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

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.

Python3




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
            break
         
    print('string does not exist in a file')


Output:

string does not exist in a file


Last Updated : 14 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads