Iterate lazily over the open file object inside a generator expression passed to sum(1 for _ in f) (or read fixed-size binary chunks via iter(lambda: f.read(1024 * 1024), b"") and count b"\n" occurrences in C), which streams multi-gigabyte files in $O(1)$ constant memory without ever loading the entire file into RAM like f.readlines() or f.read().splitlines().
Basic Example
from functools import partial
# 1. Recommended (Cleanest & O(1) memory — text streaming):
def count_lines_streaming(filepath: str, encoding: str = "utf-8") -> int:
with open(filepath, "r", encoding=encoding, errors="replace") as f:
return sum(1 for _ in f)
# 2. Fastest for multi-GB files (O(1) memory + C-level chunked b"\n" counting):
def count_lines_fast_binary(filepath: str, chunk_size: int = 1024 * 1024) -> int:
count = 0
last_byte = b""
with open(filepath, "rb") as f:
for chunk in iter(partial(f.read, chunk_size), b""):
count += chunk.count(b"\n")
last_byte = chunk[-1:]
# Add 1 if the file is non-empty and does not end with a trailing newline:
if last_byte and last_byte != b"\n":
count += 1
return count
Key Details & Edge Cases
- Never use
len(f.readlines())orlen(f.read().splitlines())on large files:- Both read the entire file into memory at once and allocate a Python
strobject for every single line—a 4 GB log file can easily consume 8 GB–16 GB of RAM and trigger anMemoryErroror OS OOM kill.
- Both read the entire file into memory at once and allocate a Python
- Note the
enumerate()trap on empty files (0lines vs.1line):- A common anti-pattern
for i, _ in enumerate(f, 1): pass; return iraisesUnboundLocalErroron a 0-byte empty file unlessi = 0is initialized beforehand.sum(1 for _ in f)handles empty files cleanly and returns0.
- A common anti-pattern
- Trailing newline discrepancy between
sum(1 for _ in f)andchunk.count(b"\n"):- Python’s line iterator (
for _ in f) counts a final line even if the file lacks a trailing\n(b"a\nb"yields 2 lines, matchingwc -lonly when trailing\nis present—note Unixwc -lstrictly counts\ncharacters and returns1forb"a\nb"!). Thelast_byte != b"\n"check incount_lines_fast_binary()keeps binary chunk counting 100% consistent withsum(1 for _ in f).
- Python’s line iterator (
- Encoding resilience when counting lines in arbitrary text logs:
- Opening in text mode (
"r") with default strict UTF-8 raisesUnicodeDecodeErrorif a multi-gigabyte log file contains a single corrupt byte. Either passerrors="replace"in text mode or open in binary mode ("rb"), which skips Unicode decoding completely (3x–5x faster and immune to encoding errors).
- Opening in text mode (
- Avoid
mmapon 32-bit systems or files larger than available address space:- While
mmap.mmap()is fast on 64-bit systems, chunked binaryf.read(1024 * 1024)works reliably across all platforms, pipes, compressed streams (gzip.open), and files larger than RAM without virtual-memory mapping overhead.
- While
Comparison of Line-Counting Methods in Python
| Method | Peak Memory Usage | Speed on Multi-GB Files | Safe on Corrupt UTF-8 Bytes? | Best Used When |
|---|---|---|---|---|
sum(1 for _ in open(path, "rb")) (Recommended for simplicity) |
$O(1)$ (~8 KB buffer) | Fast (~2–3x faster than UTF-8 text mode) | Yes ("rb" skips decoding) |
Standard large files where clean, readable, idiomatic code is prioritized. |
Chunked f.read(1 << 20) + chunk.count(b"\n") (Recommended for max speed) |
$O(1)$ (1 MB buffer) | Fastest (~5x–10x faster than text iteration) | Yes | Multi-gigabyte logs, CSVs, or datasets where maximum throughput matters. |
sum(1 for _ in open(path, encoding="utf-8", errors="replace")) |
$O(1)$ (~8 KB buffer) | Moderate (decodes every character) | Yes (with errors="replace") |
When universal newline normalization (\r\n, \r, \n) is strictly required. |
len(f.readlines()) / len(f.read().splitlines()) (Avoid) |
$O(N)$ (entire file + line list in RAM) | Fast on tiny files, crashes on large files | No (unless errors="replace") |
Tiny config files (< 1 MB) already being loaded completely into a list. |
You must log in or register to comment.
