Python Practice › File Handling Programs › Program 10
Count a word in a file
Write a Python program to count how many times a word occurs in a file.
Output
4
Approach
- Lower-case the words and count matches.
Solution
with open("story.txt", "w") as f: f.write("Test early. Test often.\nA good test is a fast test.\n") with open("story.txt") as f: words = [w.strip(".,").lower() for w in f.read().split()]print(words.count("test"))Output
4
Line by line
Line 5
Stripping punctuation and lower-casing makes “Test”, “test.” and “test” match.
Learn the concept
New to this topic? Read the lesson, then come back.