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
Run in browser1# 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.