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
Run in browser
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.