Python Practice › File Handling Programs › Program 14
Count all words in a file
Write a Python program to count all the words in a file.
Output
8
Approach
- Sum the word count of each line.
Solution
with open("story.txt", "w") as f: f.write("Python is fun\nFiles are easy to read\n") with open("story.txt") as f: print(sum(len(line.split()) for line in f))Output
8
Learn the concept
New to this topic? Read the lesson, then come back.