Python Practice › Loop Programs › Program 82

Count characters in a file

EasyLoop Programs · 82 of 90

Write a Python program to count the characters in a file (letters, digits, punctuation and spaces, not counting newlines).

Advertisement
Input
file.txt: "I'm learning python" / "At" / "Sqatools"
Output
29

Approach

  1. Read the file line by line and add the length of each line without its newline.

Solution

Python
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.

More loop programs

← All 90 Loop Programs

Leave a Comment