0
0
PythonProgramBeginner · 2 min read

Python Program to Count Lines in a File

Use with open('filename', 'r') as file: lines = sum(1 for line in file) to count lines in a file in Python.
📋

Examples

Inputfile content: Hello\nWorld\n
Output2
Inputfile content: (empty file)
Output0
Inputfile content: Line1\nLine2\nLine3\nLine4\n
Output4
🧠

How to Think About It

To count lines in a file, open the file in read mode, then read each line one by one and keep a count. The total count after reading all lines is the number of lines in the file.
📐

Algorithm

1
Open the file in read mode.
2
Initialize a counter to zero.
3
For each line in the file, increase the counter by one.
4
After reading all lines, close the file.
5
Return or print the counter value.
💻

Code

python
filename = 'sample.txt'
with open(filename, 'r') as file:
    line_count = sum(1 for line in file)
print(f'Total lines: {line_count}')
Output
Total lines: 4
🔍

Dry Run

Let's trace counting lines in a file with 4 lines: 'Line1\nLine2\nLine3\nLine4\n'.

1

Open file

Open 'sample.txt' in read mode.

2

Count lines

Read each line and count: Line1 (count=1), Line2 (count=2), Line3 (count=3), Line4 (count=4).

3

Close file

File is automatically closed after the with block.

4

Print result

Print 'Total lines: 4'.

Line ContentCount After Reading
Line11
Line22
Line33
Line44
💡

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

Using readlines()
python
filename = 'sample.txt'
with open(filename, 'r') as file:
    lines = file.readlines()
    line_count = len(lines)
print(f'Total lines: {line_count}')
Reads all lines into memory at once, which can be slower and use more memory for large files.
Using a loop and counter
python
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}')
Explicit loop is clear and memory efficient, good for beginners to understand counting.

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.

ApproachTimeSpaceBest For
Generator expression with sumO(n)O(1)Large files, memory efficient
readlines() and len()O(n)O(n)Small files, simple code
Explicit loop and counterO(n)O(1)Clear logic, beginner-friendly
💡
Use with to open files so they close automatically and avoid resource leaks.
⚠️
Forgetting to open the file in read mode or not closing the file after reading.