Count Characters in File
Count the total number of characters in a text file.
BeginnerTopic: File Handling Programs
Python Count Characters in File Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to count characters in a file
filename = input("Enter filename: ")
try:
with open(filename, "r", encoding="utf-8") as f:
text = f.read()
print("Character count:", len(text))
except FileNotFoundError:
print("File not found.")Output
Enter filename: notes.txt Character count: 120
Understanding Count Characters in File
len(text) returns the total number of characters including spaces and newlines.
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.