Count Characters in File in Python

Count the total number of characters in a text file.

BeginnerFile Handling ProgramsExample 14 of 20
count-characters-in-file.py
1# Program to count characters 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 print("Character count:", len(text))
9except FileNotFoundError:
10 print("File not found.")

Output

Enter filename: notes.txt
Character count: 120

What's going on

len(text) returns the total number of characters including spaces and newlines.

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.