Count Words in File in Python

Count the number of words in a text file.

BeginnerFile Handling ProgramsExample 12 of 20
count-words-in-file.py
1# Program to count words in a file
2
3filename = input("Enter filename: ")
4
5try:
6 with open(filename, "r", encoding="utf-8") as f:
7 text = f.read()
8 words = text.split()
9 print("Word count:", len(words))
10except FileNotFoundError:
11 print("File not found.")

Output

Enter filename: notes.txt
Word count: 42

What's going on

Splitting on whitespace with .split() gives a simple word count metric.

After this program

If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.