Python program to search for a text in a file

Python program to search for a text in a file:

This post will show you how to search for a specific text in a text file in Python. It will check for a pattern in the file.

For example, if the file includes the text hello world and if we are searching for world, it will return True. Also, if we search for rld, it will return True since rld is in the file text.


The first thing we need to do is to open the file in read mode. Then, we will iterate or read each lines of the file and we will check if the given text is present in the line or not. If it is, it will return True. Else, it will return False.

In short,

  • Open the file
  • Iterate through the lines one by one
  • Check if the pattern is found in any line
  • If found, return True, else return False

Python program:

Below is the complete python program:

import re

text_found = False
given_file = open('input.txt', 'r')
text_to_search = input('Enter a string to search : ')

for line in given_file:
    if, line):
        text_found = True

if text_found:
    print('It is in the file !!')
    print('Sorry, try again !!')



  • text_found is a flag to define if the text is found in the file or not. It is initialized as False.
  • given_file is the file that we are reading. It is open in read mode.
  • text_to_search is the text or pattern we want to search in the file. This text is read as input from the user.
  • The for loop runs through the lines of the file one by one. For each line, it searches for the text or text_to_search by using If it is found, it marks text_found as True and exits from the loop.
  • The if-else block at the end of the program checks the value of text_found. Based on its value, it prints one message if the word is in the file or not.

python search text in file

Sample Output:

For this example, the input.txt file includes the below text:

The quick brown
jumps over
the lazy dog

If you run it, it will give output as like below:

Enter a string to search : fox
It is in the file !!

Enter a string to search : laz
It is in the file !!

Enter a string to search : bear
Sorry, try again !!

Enter a string to search : jumps over
It is in the file !!

You might also like: