Editor

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

  1. 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.
  2. enumerate(f, start=1) gives each line together with its line number, counting from 1.
  3. line.split() breaks the line into words, and w.strip(".,!?") removes punctuation from the ends of each word.
  4. Comparing in lower case means "Python" and "python" both match, while a longer word such as "pythonic" does not.
  5. total adds 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.

All Python programs · CBSE class 12 practical file · Python exercises