0
0
PythonHow-ToBeginner · 3 min read

How to Count Lines in a File in Python Quickly and Easily

To count lines in a file in Python, open the file using open() and iterate through each line, counting them. You can use a simple loop or the built-in sum(1 for line in file) expression to get the total line count.
📐

Syntax

Use open(filename, mode) to open a file, then iterate over the file object to read lines one by one. Counting lines can be done by adding 1 for each line read.

  • filename: The path to your file as a string.
  • mode: Usually 'r' for reading.
  • Iterate over the file object to access each line.
python
with open('filename.txt', 'r') as file:
    line_count = sum(1 for line in file)
💻

Example

This example opens a file named example.txt and counts how many lines it contains, then prints the result.

python
with open('example.txt', 'r') as file:
    line_count = sum(1 for line in file)
print(f'The file has {line_count} lines.')
Output
The file has 4 lines.
⚠️

Common Pitfalls

One common mistake is reading the file twice without resetting the file pointer, which results in zero lines counted the second time. Another is forgetting to close the file, which with handles automatically.

Also, counting lines by reading the entire file into memory with readlines() can be inefficient for large files.

python
with open('example.txt', 'r') as file:
    lines = file.readlines()
    print(len(lines))  # Works but loads whole file into memory

with open('example.txt', 'r') as file:
    line_count = sum(1 for line in file)  # Efficient and memory-friendly
print(line_count)
Output
4
📊

Quick Reference

MethodDescriptionWhen to Use
sum(1 for line in file)Counts lines by iterating file onceBest for large files, memory efficient
len(file.readlines())Reads all lines into a list then countsSimple but uses more memory
Manual loop with counterIncrement counter for each line readGood for adding extra processing per line

Key Takeaways

Use with open(filename, 'r') to safely open and close files.
Count lines efficiently with sum(1 for line in file) to avoid loading entire file into memory.
Avoid reading the file twice without resetting the pointer; use with to manage file context.
For very large files, iterating line by line is best to save memory.
Remember to handle file paths and errors in real applications.