You write a pipeline to process a 40 GB JSONL or CSV export, and it blows past memory limits within three minutes. Or it silently truncates fields, chokes on Windows-1252 quotes mixed into an alleged UTF-8 stream, or dies halfway through because pathlib.Path.glob returned paths out of order.
These files are too big to load into memory with json.load() or pandas.read_csv(), but naive line-by-line iteration brings its own set of traps.
textTraceback (most recent call last):
File "process_dumps.py", line 42, in <module>
for row in reader:
File "C:\Python312\Lib\csv.py", line 111, in __next__
row = next(self.reader)
_csv.Error: field larger than field limit (131072)
Or you hit this variant fifty gigabytes into an overnight run:
textUnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 8412: invalid start byte
Here is why these failures happen and how to write streaming pipelines that do not collapse under dirty input.
The naive approach and why it breaks
Developers usually start with code like this:
python# leaky_pipeline.py
import json
from pathlib import Path
dump_dir = Path("./data_dumps")
for path in dump_dir.glob("*.jsonl"):
with path.open("r") as f:
data = [json.loads(line) for line in f]
# do something with data
This pattern has four distinct failure modes on large datasets:
path.open("r")defaults tolocale.getpreferredencoding(False). On Windows, that is oftencp1252, not UTF-8. Your script runs on macOS in dev and crashes in production on a Windows runner or container.- The list comprehension reads the entire file into memory before yielding anything. If a single file is 12 GB, a machine with 8 GB of RAM will page to disk and invoke the OOM killer.
- Standard
Path.glob()does not guarantee deterministic order across platforms. On Linux it follows directory entry order fromreaddir(). On Windows it follows NTFS B-tree traversal. Your records process out of sequence. - Python’s default CSV parser limits field sizes to 128 KB. If someone exported raw HTML, markdown notes, or nested JSON into a single CSV cell, the parser throws
_csv.Error.
The streaming generator pattern
Streaming files safely requires generators that yield parsed records one at a time, explicit encoding declarations, and surrogate error handling.
Here is a hardened reader for JSONL:
pythonimport json
from collections.abc import Iterator
from pathlib import Path
from typing import Any
def stream_jsonl(file_path: Path) -> Iterator[dict[str, Any]]:
# newline="" lets Python pass raw newline bytes to json decoders without translation
with file_path.open(mode="r", encoding="utf-8", errors="surrogateescape", newline="") as f:
for line_number, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
yield json.loads(line)
except json.JSONDecodeError as err:
# Log the line number and offending data slice rather than crashing
raise ValueError(f"Invalid JSON at {file_path}:{line_number}: {err.msg}") from err
Using errors="surrogateescape" is critical when you do not control the upstream source. Instead of throwing a UnicodeDecodeError on an unexpected Windows-1252 byte (like 0x92 for a smart quote), Python replaces the byte with a private surrogate code point. If you write the record back out with errors="surrogateescape", the exact original byte sequence is preserved without corrupting the file or crashing the worker.
Handling CSV field size limits and embedded nulls
The csv module requires different tuning. The standard library parser is implemented in C and relies on fixed buffers.
pythonimport csv
import sys
from collections.abc import Iterator
from pathlib import Path
def configure_csv_limits() -> None:
# Increase the field size limit to system maximum
max_limit = sys.maxsize
while True:
try:
csv.field_size_limit(max_limit)
break
except OverflowError:
# sys.maxsize can overflow C long on some platforms (like 64-bit Windows)
max_limit = int(max_limit / 10)
def stream_csv(file_path: Path) -> Iterator[dict[str, str]]:
configure_csv_limits()
with file_path.open(mode="r", encoding="utf-8-sig", errors="surrogateescape", newline="") as f:
# utf-8-sig automatically strips the UTF-8 BOM if present
reader = csv.DictReader(f)
for row in reader:
yield row
Notice the encoding: utf-8-sig. Windows exports from SQL Server or Excel often prepend a three-byte Byte Order Mark (\xef\xbb\xbf). If you open that file with standard utf-8, your first dictionary key will be "\ufeffid" instead of "id". Every lookup for row["id"] will raise a KeyError. utf-8-sig reads both standard UTF-8 and BOM-prepended UTF-8 transparently.
Pathlib gotchas when traversing multi-gigabyte structures
Path.glob() creates concrete iterator objects, but naive usage causes silent sorting bugs and resource starvation.
1. Deterministic ordering
Never rely on bare Path.glob() if processing order matters (for instance, when ingesting daily append logs). Always sort the results explicitly:
pythondump_dir = Path("/var/data/exports")
# BAD: non-deterministic across filesystems
# files = dump_dir.glob("*.csv")
# GOOD: explicit sorting ensures reproducible state
files = sorted(dump_dir.glob("*.csv"), key=lambda p: p.name)
2. The Path.resolve() network share freeze on Windows
If you run your processing scripts on Windows against UNC paths or mapped drives (e.g., \\storage\analytics), calling path.resolve() on every file in a loop will destroy your throughput.
path.resolve() calls GetFinalPathNameByHandle under the hood. On network shares, this creates an SMB handle query over the network for every single entry.
python# Slow: performs network round-trips for each item
# full_path = entry.resolve()
# Fast: stays strictly lexical, zero I/O calls
full_path = entry.absolute()
Use path.absolute() unless you explicitly need symlink resolution.
Edge case 1: Embedded newlines inside JSONL records
JSONL requires that each JSON object exists strictly on a single line. However, dirty source exporters sometimes fail to escape literal newlines within string fields:
text{"id": 101, "comment": "First line
second line"}
{"id": 102, "comment": "Clean record"}
Standard iteration for line in f: will read the first half of object 101, attempt json.loads(), and raise json.JSONDecodeError: Unterminated string starting at line 1 column 24.
To handle unescaped newlines in large files without buffering everything in RAM, use an accumulator buffer that consumes lines until json.loads succeeds:
pythondef stream_repaired_jsonl(file_path: Path) -> Iterator[dict[str, Any]]:
with file_path.open("r", encoding="utf-8", errors="surrogateescape") as f:
buffer = ""
start_line = 1
for line_num, line in enumerate(f, start=1):
if not buffer:
start_line = line_num
buffer += line
try:
record = json.loads(buffer)
yield record
buffer = ""
except json.JSONDecodeError:
# If buffer grows past a sane limit, it is garbage data, not a split string
if len(buffer) > 10 * 1024 * 1024: # 10MB limit
raise ValueError(f"Record starting at line {start_line} exceeds max buffer size")
continue
if buffer.strip():
raise ValueError(f"Dangling unclosed record starting at line {start_line}")
Edge case 2: Embedded NUL bytes in CSV data
Postgres and MySQL exports containing binary data or malformed text often leak null bytes (\x00). Python’s internal _csv module is written in C and treats \x00 as a null terminator, throwing an immediate exception:
text_csv.Error: line contains NUL
You cannot solve this inside csv.reader directly because the underlying C code throws before yielding. The fix is to pass a line filter generator into the CSV reader to replace null bytes on the fly:
pythondef sanitize_null_bytes(stream: Iterator[str]) -> Iterator[str]:
for line in stream:
yield line.replace("\x00", "")
def stream_dirty_csv(file_path: Path) -> Iterator[dict[str, str]]:
configure_csv_limits()
with file_path.open("r", encoding="utf-8-sig", errors="surrogateescape", newline="") as f:
clean_stream = sanitize_null_bytes(f)
reader = csv.DictReader(clean_stream)
for row in reader:
yield row
Because sanitize_null_bytes is a generator, it only processes one line at a time. The file remains fully streamed, and the memory footprint remains under 50 MB regardless of file size.
Verification
To verify that your stream does not leak memory, create a synthetic 2 GB dirty file and run it under tracemalloc:
powershell# Generate a test file on Windows PowerShell
python -c @"
with open('test_dump.jsonl', 'w', encoding='utf-8') as f:
for i in range(2_000_000):
f.write('{"id": ' + str(i) + ', "payload": "some data\x92value"}\n')
"@
Now monitor the ingestion script with memory tracking enabled:
python# verify_stream.py
import tracemalloc
from pathlib import Path
from stream_lib import stream_jsonl
tracemalloc.start()
processed = 0
target = Path("test_dump.jsonl")
for record in stream_jsonl(target):
processed += 1
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"Processed: {processed} rows")
print(f"Current memory: {current / 1024 / 1024:.2f} MB")
print(f"Peak memory: {peak / 1024 / 1024:.2f} MB")
Run the check:
textProcessed: 2000000 rows
Current memory: 0.04 MB
Peak memory: 0.12 MB
Peak memory remains negligible. The garbage collector reclaims the record reference at the start of every iteration, and the underlying stream buffers hold only small chunks of data.