In this tutorial we will learn how to find a string in a text file using Python.
How to find a string in a text file using Python
To find a string in a text file in Python, open the file with its built-in open() function and then search for the string using the string manipulation methods.
Here's an example:
# Open the text file in read mode
with open('file.txt', 'r') as file:
# Loop through each line in the file
for line in file:
# Check if the string is in the line
if 'string_to_find' in line:
print('Found the string!')
Replace file.txt with the path to your text file and string_to_find with the string you wish to search for in this example.. The with
statement automatically closes the file after the search is complete.
You may use the re module to execute a regular expression search to discover all occurrences of the string in the file:
import re
# Open the text file in read mode
with open('file.txt', 'r') as file:
# Read the entire file into a string
file_contents = file.read()
# Use regex to find all occurrences of the string
matches = re.findall('string_to_find', file_contents)
# Print the number of matches found
print(f'Found {len(matches)} occurrences of the string!')
In this example, replace file.txt with the location to your text file and string_to_find with the string you want to find.The method re.findall() produces a list of all regular expression matches in the given text that are not overlapping.