Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 24 Aug, 2022
View Discussion
Improve Article
Save Article

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

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.

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 return 0
        if row.find(word) == 0:
            print('string exists in file')
              print('line Number:', lines.index(line))

Output:

-1
-1
0
string exists in file
line Number: 4
-1
-1

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.

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

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.

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!