Programming languages · Intermediate · 22 min
Process large files lazily with Python generators and itertools
By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)
You will measure how much memory a 2-million-line CSV costs when loaded into a list, rewrite the summary as a pipeline of generators and itertools that stays flat in memory, and finish with a reusable read-filter-aggregate command.
On this page
Exports get big quickly. A month of mobile money transactions for a mid-sized agent network, a year of web server logs or a sensor feed can run to millions of lines. The obvious Python code reads the whole file into a list and loops over it. That works until the file is larger than the memory you have, which on a small cloud server or an older laptop comes sooner than you expect.
Generators fix this. A generator produces one item at a time and only when asked, so a pipeline of them holds one row in memory however long the file is. The itertools module in the standard library adds the pieces you need to slice, batch, group and join those streams without building lists.
In this tutorial you generate a 2-million-line CSV of made-up mobile money transactions, measure what loading it costs, then rebuild the same summary lazily and watch the memory stay flat. You also learn the two things that catch people out: a generator can be used only once, and one you stop early should be closed. Everything is standard library, so there is nothing to install. The commands use python3.15; use whichever name runs Python 3.15 on your machine.
Step 1 · Generate a 2-million-line transactions file
Make a demo folder and write a script that creates the data. Each row is one transfer: an ID, the day, the city, its currency, the kind of transaction, the amount in whole units and whether it succeeded. A fixed random seed makes the file the same every time you run it:
mkdir -p ~/lazy-demo
cd ~/lazy-demo
cat > make_data.py <<'PY'
import csv
import random
from datetime import date, timedelta
REGIONS = [
("Lagos", "NGN"),
("Nairobi", "KES"),
("Accra", "GHS"),
("Kampala", "UGX"),
("Kigali", "RWF"),
("Dar es Salaam", "TZS"),
]
KINDS = ["send", "receive", "airtime", "cash_out", "bill"]
ROWS = 2_000_000
DAYS = 30
rng = random.Random(42)
start = date(2026, 10, 1)
with open("transactions.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["id", "day", "region", "currency", "kind", "amount", "status"])
for i in range(ROWS):
day = start + timedelta(days=i * DAYS // ROWS)
region, currency = rng.choice(REGIONS)
writer.writerow([
i + 1,
day.isoformat(),
region,
currency,
rng.choice(KINDS),
rng.randint(50, 50_000),
"failed" if rng.random() < 0.03 else "ok",
])
PY
python3.15 make_data.py
wc -l transactions.csv
ls -lh transactions.csv
head -n 4 transactions.csvThe rows are written in day order, from 1 October to 30 October. That matters later, when you group by day. Each city has one currency, so totals per city never mix NGN with KES.
Check it worked
wc -l prints 2000001 transactions.csv: 2 million rows plus the header. ls -lh shows a file of roughly 90 to 100 MB. head prints the header line and three rows that start with 1,2026-10-01,, 2,2026-10-01, and 3,2026-10-01,.
Step 2 · Measure the load-everything version
Write the summary the usual way first: read every line into a list, then add up the successful amounts per city. tracemalloc from the standard library records how much memory Python allocates, and get_traced_memory() returns the current and the peak figure in bytes. The script saves its totals and its peak to a JSON file so you can compare the versions later:
mkdir -p results
cat > list_summary.py <<'PY'
import csv
import json
import tracemalloc
tracemalloc.start()
with open("transactions.csv", newline="", encoding="utf-8") as f:
lines = f.readlines()
totals = {}
for row in csv.reader(lines[1:]):
if row[6] == "ok":
key = f"{row[2]} {row[3]}"
totals[key] = totals.get(key, 0) + int(row[5])
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
for key in sorted(totals):
print(f"{key:<18}{totals[key]:>16,}")
print(f"peak memory: {peak / 1_000_000:.1f} MB")
with open("results/list.json", "w", encoding="utf-8") as out:
json.dump({"peak_mb": peak / 1_000_000, "totals": totals}, out)
PY
python3.15 list_summary.pyf.readlines() builds a list with one string object per line. Each string carries some 50 bytes of overhead on top of its text, so the list costs more than twice the size of the file. lines[1:], which skips the header, makes a second list of the same length.
Check it worked
The script prints six lines, one per city and currency, each with a large total, then a line like peak memory: 210.2 MB. Your figure will differ a little, but it is in the hundreds of megabytes. tracemalloc counts only memory Python allocates for objects, so the process as a whole uses somewhat more than this.
Step 3 · Rewrite the summary as a generator pipeline
A function that contains yield is a generator function. Calling it runs none of its body; it returns a generator object. Each time a loop asks for the next item, the body runs until the next yield, hands over one value and pauses there, with its local variables and open file kept as they were.
Put the reading and parsing in a small module you can reuse in the next steps:
cat > lazy.py <<'PY'
import csv
from typing import NamedTuple
class Txn(NamedTuple):
id: int
day: str
region: str
currency: str
kind: str
amount: int
status: str
def read_rows(path):
"""Yield each data row of a CSV file as a list of strings."""
with open(path, newline="", encoding="utf-8") as f:
reader = csv.reader(f)
next(reader) # skip the header
for row in reader:
yield row
def parse(rows):
"""Turn raw rows into Txn records, one at a time."""
return (
Txn(int(r[0]), r[1], r[2], r[3], r[4], int(r[5]), r[6])
for r in rows
)
def successful(txns):
return (t for t in txns if t.status == "ok")
PY
cat > gen_summary.py <<'PY'
import json
import tracemalloc
import lazy
tracemalloc.start()
totals = {}
for t in lazy.successful(lazy.parse(lazy.read_rows("transactions.csv"))):
key = f"{t.region} {t.currency}"
totals[key] = totals.get(key, 0) + t.amount
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
for key in sorted(totals):
print(f"{key:<18}{totals[key]:>16,}")
print(f"peak memory: {peak / 1_000_000:.3f} MB")
with open("results/list.json", encoding="utf-8") as f:
print("same totals as the list version:", json.load(f)["totals"] == totals)
with open("results/gen.json", "w", encoding="utf-8") as out:
json.dump({"peak_mb": peak / 1_000_000, "totals": totals}, out)
PY
python3.15 gen_summary.pyparse and successful use generator expressions: the same syntax as a list comprehension, but in round brackets, so they produce items on demand instead of building a list. The file object itself is lazy too. Looping over it reads a buffer at a time, and csv.reader takes one line from it whenever it needs one.
Nothing happens until the for loop in gen_summary.py asks for a transaction. That request travels back through successful, parse and read_rows to the file, and one row comes forward through each stage. Only then is the next line read.
Check it worked
The six totals are the same as in the previous step, and the script prints same totals as the list version: True. The peak is now a fraction of a megabyte, something like peak memory: 0.176 MB, against hundreds of megabytes before. It does not grow with the length of the file, because only one row is alive at a time.
Step 4 · See that a generator runs once, and close one early
A generator remembers where it stopped and never starts again. Use itertools.islice to take the first few items, which is the lazy version of rows[:3], and then see what is left:
cat > once.py <<'PY'
from itertools import islice
import lazy
txns = lazy.parse(lazy.read_rows("transactions.csv"))
for t in islice(txns, 3):
print(t)
print("left after taking 3:", sum(1 for _ in txns))
print("left on a second pass:", sum(1 for _ in txns))
# Stopping early: the file stays open until the generator is closed.
opened = []
def read_lines(path):
with open(path, encoding="utf-8") as f:
opened.append(f)
yield from f
lines = read_lines("transactions.csv")
print("first line:", next(lines).strip())
print("file open while paused:", not opened[0].closed)
lines.close()
print("file open after close():", not opened[0].closed)
PY
python3.15 once.pysum(1 for _ in txns) counts items by pulling them all through, which empties the generator. The second count therefore finds nothing. No error is raised: an exhausted generator looks exactly like an empty one, which is why this bug can go unnoticed.
yield from f hands over every item of f in turn, as a shorter way to write for line in f: yield line. A generator paused inside a with block keeps its file open. Calling close() raises GeneratorExit at the paused yield, so the with block exits and the file is closed. If you stop a for loop with break, the generator is closed only when it is garbage-collected. In code that opens many files, close it yourself, or wrap it in contextlib.closing(...) so a with block does it for you.
When a list is still the right choice
Laziness is not always better. Build a list when:
- you need the data more than once, and reading the source again is slow or impossible (a network stream, for example)
- you need
len(), indexing, slicing from the end orsorted(), which all need every item anyway - the data is small: a few thousand rows fit easily in memory, and a list is simpler to inspect and debug
If you need two passes over a large file, call the generator function again for a fresh generator rather than turning the first one into a list.
Check it worked
The first three lines are Txn(id=1, day='2026-10-01', ...) records for IDs 1, 2 and 3. Then the script prints left after taking 3: 1999997 and left on a second pass: 0. The last three lines are the header (first line: id,day,region,currency,kind,amount,status), file open while paused: True and file open after close(): False.
Step 5 · Send records in fixed-size batches with batched
Lazy reading meets a common need: sending rows to an API or a database in chunks, so you neither make two million calls nor build one enormous request. itertools.batched groups any iterable into tuples of a fixed size, with a shorter final batch if the count does not divide evenly:
cat > batches.py <<'PY'
from itertools import batched
import lazy
def send(batch):
"""Stand-in for a bulk API call or a database insert."""
return len(batch)
txns = lazy.successful(lazy.parse(lazy.read_rows("transactions.csv")))
batches = rows = last = 0
for batch in batched(txns, 10_000):
rows += send(batch)
batches += 1
last = len(batch)
print(f"batches: {batches}, rows sent: {rows:,}, last batch: {last}")
PY
python3.15 batches.pyAt most one batch of 10,000 records is in memory at a time. Replace send with your real call, and set the batch size to what the receiving service accepts. Smaller batches also help when the connection is slow or charged by the megabyte, as on many prepaid mobile data plans: a failed request costs one small batch to retry, not the whole upload. Pass strict=True to batched if a short final batch would be an error in your case; it then raises ValueError.
Check it worked
The script prints one line like batches: 194, rows sent: 1,939,730, last batch: 9730. Your counts may differ, but rows sent is about 97% of 2 million (the generator marks about 3% of transfers as failed), batches is rows sent divided by 10,000 and rounded up, and last batch is the remainder.
Step 6 · Group sorted rows with groupby
itertools.groupby collects runs of consecutive items that share a key. It does not sort and it does not look ahead: it starts a new group every time the key changes. That makes it lazy, and also easy to misuse. The file is in day order, so grouping by day works. Grouping by city, which is mixed throughout the file, does not:
cat > daily.py <<'PY'
from itertools import groupby, islice
from operator import attrgetter
import lazy
txns = lazy.successful(lazy.parse(lazy.read_rows("transactions.csv")))
days = 0
for day, group in groupby(txns, key=attrgetter("day")):
count = total = 0
for t in group:
count += 1
total += t.amount
if days < 3:
print(f"{day} {count:>7,} transactions amount {total:>14,}")
days += 1
print("days:", days)
regions = lazy.parse(lazy.read_rows("transactions.csv"))
runs = sum(1 for _ in groupby(regions, key=attrgetter("region")))
print("groups when grouping unsorted cities:", f"{runs:,}")
PY
python3.15 daily.pyEach group is itself a lazy iterator over that day's rows, and it is valid only until groupby moves on, so use it inside the loop. Sorting a file of this size first would need the whole thing in memory, which defeats the point. When the key is not in order, add up into a dictionary keyed by the value instead, as the summary in the earlier step did.
Check it worked
The script prints three lines for 2026-10-01, 2026-10-02 and 2026-10-03, each with about 64,700 transactions, then days: 30. The last line reports well over a million groups for six cities: every time the city changes from one row to the next, groupby starts a new group.
Step 7 · Read several files as one stream with chain and yield from
Exports often arrive in parts: one file per month, per agent or per region. itertools.chain joins iterables end to end, so the rest of the pipeline sees a single stream. Create a small second file of late-arriving rows and read both:
cat > late.csv <<'CSV'
id,day,region,currency,kind,amount,status
2000001,2026-10-31,Kigali,RWF,send,1200,ok
2000002,2026-10-31,Accra,GHS,airtime,25,ok
CSV
cat > many.py <<'PY'
from itertools import chain
import lazy
def read_many(*paths):
for path in paths:
yield from lazy.read_rows(path)
files = ["transactions.csv", "late.csv"]
joined = chain.from_iterable(lazy.read_rows(p) for p in files)
print("rows with chain:", f"{sum(1 for _ in joined):,}")
last = None
for last in lazy.parse(read_many(*files)):
pass
print("rows with yield from: last id", last.id, "on", last.day)
PY
python3.15 many.pychain(a, b) takes the iterables as arguments. chain.from_iterable(...) takes them from another iterable, here a generator expression, so each file is opened only when the previous one is finished. read_many does the same job with yield from, which is the clearer choice when you want to do something per file, such as logging its name.
Check it worked
The script prints rows with chain: 2,000,002, then rows with yield from: last id 2000002 on 2026-10-31. Both ways read the two files in order, one row at a time.
Step 8 · Build a reusable read-filter-aggregate command
Turn the pattern into one script you can point at any CSV with a header row. It reads one or more files lazily with csv.DictReader, which yields each row as a dictionary keyed by the header, keeps the rows that match every --where condition and adds up one column per value of another:
cat > pipeline.py <<'PY'
"""Filter and total large CSV files without loading them into memory."""
import argparse
import csv
from collections import Counter
from itertools import islice
def read_rows(*paths):
for path in paths:
with open(path, newline="", encoding="utf-8") as f:
yield from csv.DictReader(f)
def where(rows, conditions):
return (r for r in rows if all(r[k] == v for k, v in conditions.items()))
def total_by(rows, key, column):
totals = Counter()
for r in rows:
totals[r[key]] += int(r[column])
return totals
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("files", nargs="+", help="CSV files with the same header")
parser.add_argument("--by", required=True, help="column to group by")
parser.add_argument("--sum", required=True, help="whole-number column to add up")
parser.add_argument("--where", action="append", default=[], metavar="COLUMN=VALUE",
help="keep only matching rows; repeat for more conditions")
parser.add_argument("--limit", type=int, help="read only the first N rows")
args = parser.parse_args(argv)
conditions = dict(c.split("=", 1) for c in args.where)
rows = read_rows(*args.files)
if args.limit:
rows = islice(rows, args.limit)
totals = total_by(where(rows, conditions), args.by, args.sum)
for name, value in sorted(totals.items()):
print(f"{name:<16}{value:>16,}")
if __name__ == "__main__":
main()
PY
python3.15 pipeline.py transactions.csv --by kind --sum amount --limit 1000
python3.15 pipeline.py transactions.csv late.csv --by region --sum amount --where status=ok
python3.15 pipeline.py transactions.csv --by day --sum amount --where region=Lagos --where kind=cash_out --limit 200000The functions are small and each takes an iterable and returns one, so you can import them into other scripts and add your own stages between them. --limit puts islice at the front of the pipeline, which is handy for trying a new filter on the first thousand rows before running it on the whole file. Because the files are opened with encoding="utf-8", names in Yoruba, Swahili, Amharic or any other script come through unchanged.
DictReader creates a dictionary per row, which is slower than the plain lists in lazy.py, but each one is thrown away as soon as it has been counted, so memory stays flat. If speed matters more than convenience, use csv.reader and column positions as before.
Check it worked
The first command prints five lines, one per kind (airtime, bill, cash_out, receive, send), totalled over the first 1,000 rows only. The second prints six cities. Their totals match the earlier summaries, except that Accra is 25 higher and Kigali 1,200 higher, from the two rows in late.csv. The third prints Lagos cash-out totals for the first few days of October, covered by the first 200,000 rows.
When you have finished, delete the demo folder and the data with it:
cd ~
rm -rf ~/lazy-demoNext steps
- Turn
pipeline.pyinto a polished tool with subcommands and helpful errors: build a command-line tool in Python with argparse. - When the data fits in memory and you want to explore it, a dataframe is quicker to work with: clean a CSV file with pandas.
- Revisit the file basics that generators build on: read and write files and JSON in Python.
- Brush up on what a
forloop does with any iterable: loop over lists, ranges and dictionaries with for.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials