Python Program to Search for a Word in a File
Beginner · File handling
This program searches a text file for a word and prints every line the word appears on, with its line number, followed by how many times the word was found. The search ignores capital letters and punctuation, so "Python," and "python" both count.
Program
search_word_in_file.py
# Make a sample file to work on
with open("notes.txt", "w") as f:
f.write("Python is a popular language.\n")
f.write("Many schools teach Python, and so do colleges.\n")
f.write("Java and C++ are popular too.\n")
f.write("I am learning python every day.\n")
word = "python" # or: word = input("Enter a word to search for: ")
target = word.lower()
total = 0
with open("notes.txt", "r") as f:
for number, line in enumerate(f, start=1):
count = 0
for w in line.split():
# Ignore capitals and any punctuation stuck to the word
if w.strip(".,!?").lower() == target:
count += 1
if count > 0:
print(f"Line {number}: {line.rstrip()}")
total += count
if total > 0:
print(f'"{word}" found {total} times')
else:
print(f'"{word}" was not found in the file')
Output
Line 1: Python is a popular language. Line 2: Many schools teach Python, and so do colleges. Line 4: I am learning python every day. "python" found 3 times
How it works
- The sample file has four lines, and "python" appears on lines 1, 2 and 4, twice with a capital P and once with a comma stuck to it.
enumerate(f, start=1)gives each line together with its line number, counting from 1.line.split()breaks the line into words, andw.strip(".,!?")removes punctuation from the ends of each word.- Comparing in lower case means "Python" and "python" both match, while a longer word such as "pythonic" does not.
totaladds up the matches from every line and decides the final message.
Another way to write it
Using in and count()
Using in and count()
# Make a sample file to work on
with open("notes.txt", "w") as f:
f.write("Python is a popular language.\nJava is popular too.\n")
word = "popular"
with open("notes.txt", "r") as f:
text = f.read()
if word in text:
print(f'"{word}" is in the file, {text.count(word)} times')
else:
print(f'"{word}" is not in the file')
Output
"popular" is in the file, 2 times
in and count() look for the letters anywhere in the text, so they are quick for a yes or no answer, but they are case sensitive and would also find "popular" inside "unpopular".
Try it yourself
Search for "popular", and then for "Ruby", to see both messages.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count the Words "Me" and "My" in a Text File
- Count Words in a Text File
- Display Lines Starting with T in a Text File
- Count the Frequency of Words in a String
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
All Python programs · CBSE class 12 practical file · Python exercises