Python Practice › Loop Programs › Program 82
Count characters in a file
Write a Python program to count the characters in a file (letters, digits, punctuation and spaces, not counting newlines).
Input
file.txt: "I'm learning python" / "At" / "Sqatools"
Output
29
Approach
- Read the file line by line and add the length of each line without its newline.
Solution
with open("file.txt", "w") as f: f.write("I'm learning python\nAt\nSqatools\n") count = 0with open("file.txt") as f: for line in f: count += len(line.rstrip("\n"))print(count)Output
29
Line by line
Lines 1-2
Creates the sample file so the program runs anywhere.
Lines 6-7
rstrip("\n") removes the newline before counting.
Learn the concept
New to this topic? Read the lesson, then come back.