Count lines in a file

EasyFile Handling Programs · 20 of 38

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

Advertisement
Output
4

Approach

  1. sum(1 for _ in f) counts without storing the lines.

Solution

Python
with open("story.txt", "w") as f:    f.write("a\nb\nc\nd\n") with open("story.txt") as f:    print(sum(1 for _ in f))
Output
4

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Leave a Comment