Search Substring in File in Python
Search for a substring in a text file and report matching line numbers.
BeginnerFile Handling ProgramsExample 15 of 20
search-substring-in-file.py
1# Program to search for a substring in a file23filename = input("Enter filename: ")4term = input("Enter search term: ")56try:7 with open(filename, "r", encoding="utf-8") as f:8 for line_no, line in enumerate(f, start=1):9 if term in line:10 print(f"Found on line {line_no}: {line.strip()}")11except FileNotFoundError:12 print("File not found.")
Output
Enter filename: notes.txt Enter search term: Python Found on line 3: Learning Python basics
What's going on
Reads file line by line, checking membership of the substring and printing matching lines.
After this program
If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.