Editor

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

count_characters_in_file.py
# Make a sample file to work on
with open("story.txt", "w") as f:
f.write("Room 42 is on floor 3.\n")
f.write("Lunch is at 1 pm!\n")
with open("story.txt", "r") as f:
text = f.read() # the whole file as one string
letters = 0
digits = 0
spaces = 0
others = 0
for ch in text:
if ch.isalpha():
letters += 1
elif ch.isdigit():
digits += 1
elif ch == " ":
spaces += 1
elif ch != "\n": # newlines are not counted as symbols
others += 1
print("Total characters (with newlines):", len(text))
print("Letters:", letters)
print("Digits:", digits)
print("Spaces:", spaces)
print("Other symbols:", others)
Output
Total characters (with newlines): 41
Letters: 24
Digits: 4
Spaces: 9
Other symbols: 2

How it works

  1. f.read() reads the whole file into one string, so len(text) is the total number of characters, newlines included.
  2. The loop checks each character in turn: isalpha() for letters, isdigit() for digits, and then whether it is a space.
  3. Anything else except the newline at the end of each line, here the full stop and the exclamation mark, is counted as another symbol.
  4. 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

Counting without spaces and newlines
# Make a sample file to work on
with open("story.txt", "w") as f:
f.write("Room 42 is on floor 3.\nLunch is at 1 pm!\n")
with open("story.txt", "r") as f:
text = f.read()
visible = "".join(text.split()) # split() drops every space and newline
print("All characters:", len(text))
print("Without spaces and newlines:", len(visible))
Output
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

Characters on each line
# Make a sample file to work on
with open("story.txt", "w") as f:
f.write("Room 42 is on floor 3.\nLunch is at 1 pm!\n")
with open("story.txt", "r") as f:
for number, line in enumerate(f, start=1):
line = line.rstrip("\n") # do not count the newline
print(f"Line {number} has {len(line)} characters: {line}")
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises