Sub topic 12
Processing large files with JSON Lines and row-by-row iteration
This chapter assumes you can use json.load, json.dumps, csv.reader, and csv.DictReader. You should also know how to open files with with, and how generators and yield work. The earlier chapters on encodings and newline='' apply here unchanged.
Why loading everything stops working
json.load(f) reads the whole document and builds every Python object before it returns. A 2 GB JSON array can need several times that in RAM, because each small dict, string, and int carries object overhead. The program may run slowly, get killed by the operating system, or fail only on production-sized input.
A single JSON document also cannot be parsed incrementally with the standard library. The parser needs the closing bracket before it returns anything. You have two ways out:
- Store the data in a format where each record stands alone, such as JSON Lines.
- Read a format that is already record-oriented, such as CSV, one row at a time.
Both approaches keep memory use proportional to one record, not to the whole file.
The JSON Lines format
JSON Lines (also called NDJSON, newline-delimited JSON) has three rules:
- Each line is one complete, valid JSON value. In practice it is almost always an object.
- Lines are separated by
\n. - The file is UTF-8 text.
There is no enclosing array and no commas between records. The usual file extension is .jsonl.
This works because json.dumps never emits a raw newline when indent is left at its default of None. Newlines inside strings are escaped as \n, so a record always fits on one physical line.
import json
events = [{"id": 1, "type": "login"}, {"id": 2, "type": "logout"}]
with open("events.jsonl", "w", encoding="utf-8") as f:
for event in events:
f.write(json.dumps(event) + "\n")
with open("events.jsonl", encoding="utf-8") as f:
for line in f:
print(json.loads(line)["type"])The for line in f loop is the key. A text file object is an iterator that reads a buffered chunk and hands you one line at a time. Memory use stays flat whether the file has ten lines or ten million.
Reading JSON Lines safely
The minimal loop has two problems. Blank lines, such as a trailing empty line, make json.loads("") raise JSONDecodeError. A single corrupt line stops the whole run without telling you where it is. A reusable generator handles both.
import json
import sys
from collections.abc import Iterator
from pathlib import Path
def read_jsonl(path, *, skip_bad=False) -> Iterator[dict]:
"""Yield one parsed record per line, reporting the line number on errors."""
with Path(path).open(encoding="utf-8") as f:
for lineno, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
yield json.loads(line)
except json.JSONDecodeError as e:
if skip_bad:
print(f"{path}:{lineno}: skipped ({e.msg})", file=sys.stderr)
continue
raise ValueError(f"{path}:{lineno}: invalid JSON ({e.msg})") from e
if __name__ == "__main__":
Path("mixed.jsonl").write_text(
'{"id": 1}\n\n{"id": 2,}\n{"id": 3}\n', encoding="utf-8"
)
print([r["id"] for r in read_jsonl("mixed.jsonl", skip_bad=True)])Running this prints a warning for line 3 on standard error, then [1, 3]. With skip_bad=False the same call raises ValueError naming mixed.jsonl:3.
Skipping bad lines is a policy decision, not a default. Dropping records silently can corrupt a downstream report. For important data, count the skipped lines and fail the job if the count passes a threshold you choose.
Because read_jsonl is a generator, nothing is read until you iterate it. The with block stays open while the generator is suspended, and it closes when the generator is exhausted or garbage-collected. If you stop early, for example with break, call .close() on the generator or wrap it in contextlib.closing so the file closes promptly.
Writing JSON Lines incrementally
A writer can also work record by record. It never needs the full list in memory, only an iterable.
import json
from collections.abc import Iterable
from pathlib import Path
def write_jsonl(path, records: Iterable[dict], *, append=False) -> int:
"""Write records one per line. Return how many were written."""
mode = "a" if append else "w"
count = 0
with Path(path).open(mode, encoding="utf-8") as f:
for record in records:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
count += 1
return count
if __name__ == "__main__":
n = write_jsonl("squares.jsonl", ({"n": i, "sq": i * i} for i in range(100_000)))
print(n)Two details matter here.
- Appending. Mode
"a"adds records to the end of an existing file. This is a main advantage of JSON Lines over a JSON array. Appending to an array would mean rewriting the closing]and adding a comma. ensure_ascii=False. This writes characters likeüdirectly instead of as\u00fcescapes. It is safe because you opened the file as UTF-8. If you leave it at the default, the file stays pure ASCII, which is more portable but larger for non-English text.
A crash during a write can leave a final line cut in half. Readers that skip bad lines survive this. Readers that don't will fail on the last line, which tells you the file was truncated.
Row-by-row CSV
csv.reader and csv.DictReader are already iterators. They pull lines from the file as you ask for them, so a loop over the reader is streaming by default.
import csv
from pathlib import Path
Path("sales.csv").write_text(
"region,amount\nnorth,10.50\nsouth,3.25\nnorth,4.00\n", encoding="utf-8"
)
totals: dict[str, float] = {}
with open("sales.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
totals[row["region"]] = totals.get(row["region"], 0.0) + float(row["amount"])
print(totals) # {'north': 14.5, 'south': 3.25}Memory here depends on the size of totals, which is the number of distinct regions. The file size does not matter. Aggregations like sums, counts, minimums, and maximums fit this pattern well.
The common mistake is calling list(reader) or rows = [r for r in reader] out of habit. That loads every row and removes the benefit. Collect rows only when you truly need them all at once, for example to sort.
Rows are not always lines
A quoted CSV field may contain a newline, so one row can span several physical lines. Do not count rows with sum(1 for _ in open(path)). Use the reader's own counters:
reader.line_numis the number of physical lines consumed so far. It is useful in error messages.enumerate(reader)counts logical rows.
import csv
from pathlib import Path
Path("notes.csv").write_text(
'id,note\n1,"two\nlines"\n2,plain\n', encoding="utf-8"
)
with open("notes.csv", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
for row_number, row in enumerate(reader):
print(row_number, reader.line_num, row)The output shows that row 2 ends on line 4, because the quoted note in row 1 occupies two lines. This is also why newline='' is required. The csv module needs to see the raw line endings to handle embedded newlines correctly.
Streaming one format into the other
Chaining generators lets you convert a large CSV into JSON Lines without ever holding more than one row. Each stage pulls from the one before it.
import csv
import json
from collections.abc import Iterable, Iterator
from pathlib import Path
Path("big.csv").write_text(
"name,qty\napple,3\npear,5\nplum,not-a-number\nfig,2\n", encoding="utf-8"
)
def read_rows(path) -> Iterator[dict]:
with open(path, newline="", encoding="utf-8") as f:
yield from csv.DictReader(f)
def convert(rows: Iterable[dict]) -> Iterator[dict]:
for row in rows:
try:
yield {"name": row["name"], "qty": int(row["qty"])}
except ValueError:
continue # a real job would count or log rejected rows
def write_lines(path, records: Iterable[dict]) -> int:
count = 0
with open(path, "w", encoding="utf-8") as f:
for record in records:
f.write(json.dumps(record) + "\n")
count += 1
return count
print(write_lines("big.jsonl", convert(read_rows("big.csv")))) # 3The plum row fails int() and is dropped, so three records are written. Every stage is lazy, so the file is read, converted, and written in a single pass.
The reverse direction works the same way. Read with read_jsonl, then feed the dicts to csv.DictWriter.writerows. That method accepts any iterable, so a generator works. DictWriter needs fieldnames up front, which a streaming job cannot discover without reading everything. Decide the columns from a schema, or read the first record and use its keys.
Batching for efficiency
Per-record work is fine for file conversion. It becomes slow when each record triggers a database insert or an HTTP request. Group records into batches of fixed size while still streaming.
from collections.abc import Iterable, Iterator
from itertools import islice
def batches(items: Iterable, size: int) -> Iterator[list]:
iterator = iter(items)
while chunk := list(islice(iterator, size)):
yield chunk
for chunk in batches(range(7), 3):
print(chunk)
# [0, 1, 2]
# [3, 4, 5]
# [6]Python 3.12 adds itertools.batched, which yields tuples. The helper above works on older versions. Memory is bounded by size records, so you choose the trade-off between memory and the number of round trips.
Choosing a format
| Situation | Better choice | Reason |
|---|---|---|
| Records are appended over time, such as logs or events | JSON Lines | Appending needs no rewrite |
| Data is flat with the same columns in every row | CSV | Smaller, opens in spreadsheets |
| Records are nested or have different fields | JSON Lines | CSV cannot hold nesting |
| One small config or API response | Plain JSON | Streaming adds nothing |
| Need random access to record N | Neither | Use a database such as SQLite |
Edge cases and failure modes
- Counting lines is a full read. Neither format has an index. Getting the record count means scanning the file once.
- No random access. Reaching record 1,000,000 means reading the first 999,999. For repeated lookups, load once into a database or build your own offset index.
- Embedded newlines. For JSON Lines this is not a problem, since
json.dumpsescapes them. For CSV, usecsvand neverline.split(","). - Windows line endings. Text-mode iteration translates
\r\nto\n, andstrip()removes any leftovers. For CSV, still passnewline=''. - Byte order mark. A file saved by some Windows tools starts with a BOM. For CSV,
encoding="utf-8-sig"strips it, otherwise your first column name becomes\ufeffname. - Mixed record shapes. JSON Lines allows each line to have different keys. Use
.get()with defaults, or validate each record, before relying on a key. - Compressed input.
gzip.open(path, "rt", encoding="utf-8")returns a text file object. Everything in this chapter works on it unchanged, and.jsonl.gzis common for large exports. - Large single field. Row-by-row reading cannot help if one row is huge.
csvraises_csv.Error: field larger than field limit (131072)when a field exceeds the default limit. You can raise it withcsv.field_size_limit, but a field that large usually signals a malformed file.
Exercise
A teammate reads a 5 GB log with records = [json.loads(line) for line in f] and then runs sum(r["bytes"] for r in records). The job runs out of memory. Rewrite the computation so memory use does not grow with file size, and say why it works.
Show answer
Use a generator expression and let sum consume it: total = sum(json.loads(line)["bytes"] for line in f), with f opened as open("log.jsonl", encoding="utf-8"). The list comprehension builds every record before sum starts. The generator expression parses one line, passes its value to sum, and discards the record before reading the next line. Only one record is alive at a time, so memory stays constant regardless of file size.
Exercise
You append records to events.jsonl with json.dumps(record, indent=2) + "\n". Later, for line in f: json.loads(line) fails on the first line with a JSONDecodeError. What went wrong, and what is the fix?
Show answer
indent=2 spreads each record over several lines. The first line is just {, which is not a complete JSON value, so parsing fails. JSON Lines needs exactly one complete value per line. Remove indent (or pass indent=None) when writing. The records already written in the indented style must be rewritten, for instance by reading the file as a stream of concatenated JSON values with json.JSONDecoder.raw_decode and rewriting each one compactly.
Exercise
A CSV file has 1,000 data rows, but sum(1 for _ in open("data.csv")) reports 1,043 lines. Give one likely cause and a way to count rows correctly.
Show answer
Some quoted fields contain embedded newlines, so a single row spans several physical lines. Count rows with the csv module: with open("data.csv", newline="", encoding="utf-8") as f: rows = sum(1 for _ in csv.reader(f)) - 1, where the subtraction removes the header row. Opening with newline='' is required so the reader sees the raw line endings.