Count all words in a file

EasyFile Handling Programs · 14 of 38

Write a Python program to count all the words in a file.

Advertisement
Output
8

Approach

  1. Sum the word count of each line.

Solution

Python
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
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs