How to search for text in a file in Python

Searching for text in a file returns all lines in a file that contain a specific string.

Solution for How to search for text in a file in Python : You can use open() to search for text in a file Call open(file_name) to open the file named file_name. Use the syntax for line in file to access each line in the previous result file. At each iteration, use string in line to check if string is in the current line. Outside of the loop, call file.close() to close file.

Use the syntax with open(file_name) as file to automatically close file once the loop finishes.

sample_file.txt


how-to-search-for-text-in-a-file-in-python