Count Words in File

Count the number of words in a text file.

PythonBeginner
Python
# Program to count words in a file

filename = input("Enter filename: ")

try:
    with open(filename, "r", encoding="utf-8") as f:
        text = f.read()
    words = text.split()
    print("Word count:", len(words))
except FileNotFoundError:
    print("File not found.")

Output

Enter filename: notes.txt
Word count: 42

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