Python Practice › File Handling Programs › Program 20
Count lines in a file
Write a Python program to count the lines in a file.
Output
4
Approach
sum(1 for _ in f)counts without storing the lines.
Solution
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.