Count characters in a file

EasyFile Handling Programs · 26 of 38

Write a Python program to count the characters in a file, with and without whitespace.

Advertisement
Output
All characters: 21
Without whitespace: 16

Approach

  1. len(text) and a count of non-whitespace characters.

Solution

Python
with open("story.txt", "w") as f:    f.write("Python is fun\nTry it\n") with open("story.txt") as f:    text = f.read()print("All characters:", len(text))print("Without whitespace:", sum(1 for ch in text if not ch.isspace()))
Output
All characters: 21
Without whitespace: 16

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Leave a Comment