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.
- 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
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 re.search(text_to_search, line): text_found = True break if text_found: print('It is in the file !!') else: 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.
- texttosearch 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 texttosearch by using re.search. 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.
For this example, the input.txt file includes the below text:
The quick brown fox 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 !!