Count digits in a file

EasyFile Handling Programs · 29 of 38

Write a Python program to count the digits in a file.

Advertisement
Output
12

Approach

  1. sum(ch.isdigit() for ch in text).

Solution

Python
with open("story.txt", "w") as f:    f.write("Order 4521 shipped on 2026-11-02\n") with open("story.txt") as f:    print(sum(ch.isdigit() for ch in f.read()))
Output
12
Advertisement

Learn the concept

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

More file handling programs

← All 38 File Handling Programs