Python Practice › File Handling Programs › Program 26
Count characters in a file
Write a Python program to count the characters in a file, with and without whitespace.
Output
All characters: 21 Without whitespace: 16
Approach
len(text)and a count of non-whitespace characters.
Solution
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.