Python Program to Count number of lines present in the file

In Python, we can count the number of lines in a file using several built-in functions and methods. This is useful for analyzing file contents or processing large text files. We'll explore different approaches to count lines efficiently.

Syntax

The basic syntax for opening a file in Python is ?

with open("filename.txt", mode) as file:
    # file operations

The open() function accepts two main parameters ?

  • filename.txt ? The name of the file to open.

  • mode ? Determines how the file is opened ('r' for reading, 'w' for writing, etc.).

Method 1: Using a Loop Counter

This approach iterates through each line and increments a counter ?

# Create a sample file first
with open('sample.txt', 'w') as f:
    f.write("Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6")

# Count lines using loop
with open('sample.txt', 'r') as file:
    count = 0
    for line in file:
        count += 1

print(f"Number of lines using loop: {count}")
Number of lines using loop: 6

Method 2: Using readlines() and len()

This method reads all lines into a list and returns its length ?

# Create a sample file first
with open('sample.txt', 'w') as f:
    f.write("Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6")

# Count lines using readlines()
with open('sample.txt', 'r') as file:
    lines = file.readlines()
    
total_lines = len(lines)
print(f"Number of lines using readlines(): {total_lines}")
Number of lines using readlines(): 6

Method 3: Using sum() with Generator Expression

A memory-efficient approach that doesn't store all lines in memory ?

# Create a sample file first
with open('sample.txt', 'w') as f:
    f.write("Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6")

# Count lines using sum() and generator
with open('sample.txt', 'r') as file:
    line_count = sum(1 for line in file)

print(f"Number of lines using sum(): {line_count}")
Number of lines using sum(): 6

Comparison

Method Memory Usage Speed Best For
Loop Counter Low Fast Simple counting
readlines() + len() High Fast Small files
sum() + Generator Very Low Fastest Large files

Handling Empty Files

Here's how to handle files that might be empty ?

# Create an empty file
with open('empty.txt', 'w') as f:
    pass

# Count lines in empty file
with open('empty.txt', 'r') as file:
    count = sum(1 for line in file)

print(f"Lines in empty file: {count}")
Lines in empty file: 0

Conclusion

Use the loop counter method for simple line counting, readlines() for small files when you need the content later, and the sum() with generator expression for memory-efficient counting of large files. All methods handle empty files correctly by returning 0.

Updated on: 2026-03-27T07:06:15+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements