LearnFrenzy
Sign in Take a free test

File Handling · File Handling Coding Problems · Question 2

Count lines, words and characters of a file in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Count the lines, words, characters and blank lines of a text file, like the Unix wc command.

Solution
main.py Run
import os, tempfile
os.chdir(tempfile.mkdtemp())
with open("story.txt", "w") as f:
    f.write("Once upon a time\nthere was a coder.\n\nThe end.\n")

lines = words = chars = blank = 0
with open("story.txt") as f:
    for line in f:
        lines += 1
        chars += len(line)
        words += len(line.split())
        blank += not line.strip()
print(f"lines={lines} words={words} chars={chars} blank={blank}")

Output Verified by running it on Python 3

lines=4 words=10 chars=46 blank=1

Iterating counts lines one at a time. A blank line strips to "", and not "" is True, which adds 1.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links