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
Run in browser1# Program to count characters in a file23filename = input("Enter filename: ")45try: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.