Python Program to Count Lines in a File
with open('filename', 'r') as file: lines = sum(1 for line in file) to count lines in a file in Python.Examples
How to Think About It
Algorithm
Code
filename = 'sample.txt' with open(filename, 'r') as file: line_count = sum(1 for line in file) print(f'Total lines: {line_count}')
Dry Run
Let's trace counting lines in a file with 4 lines: 'Line1\nLine2\nLine3\nLine4\n'.
Open file
Open 'sample.txt' in read mode.
Count lines
Read each line and count: Line1 (count=1), Line2 (count=2), Line3 (count=3), Line4 (count=4).
Close file
File is automatically closed after the with block.
Print result
Print 'Total lines: 4'.
| Line Content | Count After Reading |
|---|---|
| Line1 | 1 |
| Line2 | 2 |
| Line3 | 3 |
| Line4 | 4 |
Why This Works
Step 1: Opening the file
Using with open(filename, 'r') opens the file safely and ensures it closes automatically.
Step 2: Counting lines
The expression sum(1 for line in file) reads each line and adds 1, counting total lines efficiently.
Step 3: Outputting the count
Printing the count shows how many lines the file contains.
Alternative Approaches
filename = 'sample.txt' with open(filename, 'r') as file: lines = file.readlines() line_count = len(lines) print(f'Total lines: {line_count}')
filename = 'sample.txt' line_count = 0 with open(filename, 'r') as file: for line in file: line_count += 1 print(f'Total lines: {line_count}')
Complexity: O(n) time, O(1) space
Time Complexity
The program reads each line once, so time grows linearly with the number of lines, O(n).
Space Complexity
Using a generator expression counts lines without extra memory, so space is O(1).
Which Approach is Fastest?
Using sum(1 for line in file) is efficient and memory-friendly compared to reading all lines at once.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Generator expression with sum | O(n) | O(1) | Large files, memory efficient |
| readlines() and len() | O(n) | O(n) | Small files, simple code |
| Explicit loop and counter | O(n) | O(1) | Clear logic, beginner-friendly |
with to open files so they close automatically and avoid resource leaks.