Count Words in File
Count the number of words in a text file.
BeginnerTopic: File Handling Programs
Python Count Words in File Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# 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
Understanding Count Words in File
Splitting on whitespace with .split() gives a simple word count metric.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.