Python Program to Count the Characters in a File
Beginner · File handling
This program counts the characters in a text file: the total, and then how many are letters, digits, spaces and other symbols. Newlines are characters too, so the total includes the one at the end of each line.
Program
Total characters (with newlines): 41 Letters: 24 Digits: 4 Spaces: 9 Other symbols: 2
How it works
f.read()reads the whole file into one string, solen(text)is the total number of characters, newlines included.- The loop checks each character in turn:
isalpha()for letters,isdigit()for digits, and then whether it is a space. - Anything else except the newline at the end of each line, here the full stop and the exclamation mark, is counted as another symbol.
- This file has 41 characters: 24 letters, 4 digits, 9 spaces, 2 symbols and 2 newlines.
Other ways to write it
Counting without spaces and newlines
All characters: 41 Without spaces and newlines: 30
text.split() breaks the text at every space and newline, and "".join() glues the pieces back together with nothing between them, so only the visible characters are left.
Characters on each line
Line 1 has 22 characters: Room 42 is on floor 3. Line 2 has 17 characters: Lunch is at 1 pm!
Reading line by line and removing each newline with rstrip("\n") gives the length of every line on its own.
Try it yourself
Add a counter for uppercase letters using ch.isupper().
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Count the Lines in a File
- Count Words in a Text File
- Count Letters, Digits and Spaces in a String
- Read a Text File and Separate Words with #
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Count the Words "Me" and "My" in a Text File
All Python programs · CBSE class 12 practical file · Python exercises