Sub topic 4
Working with the chunk reader: with, iterator and get_chunk
This chapter covers the object that pd.read_csv(..., chunksize=...) returns. It assumes you know basic Python loops and context managers, and that you have used read_csv and DataFrames. The earlier chapter showed a plain for loop over the chunks. Here you will see what that object is, how to use it safely, and how to control it by hand.
What read_csv returns when you pass chunksize
Without chunksize, read_csv returns a DataFrame. With chunksize, it returns a TextFileReader. The reader holds an open file handle and a parser, and it reads rows only when you ask for them.
The reader behaves like an iterator in Python's sense. It has a position in the file, and each request moves that position forward. You cannot rewind it. To go over the file twice, create a second reader.
To follow along, create a small demo file:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 25_000
pd.DataFrame(
{
"id": range(n),
"region": rng.choice(["north", "south", "east", "west"], n),
"amount": rng.normal(100, 20, n).round(2),
}
).to_csv("demo.csv", index=False)Now open it in chunks and inspect what comes out:
import pandas as pd
with pd.read_csv("demo.csv", chunksize=10_000) as reader:
print(type(reader).__name__)
for i, chunk in enumerate(reader):
print(i, len(chunk), chunk.index[0], chunk.index[-1])The output is:
TextFileReader
0 10000 0 9999
1 10000 10000 19999
2 5000 20000 24999Three details matter here:
- Every chunk is an ordinary DataFrame with the same column names. The parser reads the header once and reuses it.
- The index continues across chunks. The second chunk starts at 10000, not 0. If you need a per-chunk index, call
reset_index(drop=True). If you concatenate chunks later, the continuous index is what you want. - The last chunk holds whatever rows remain, so it is usually smaller than
chunksize.
The reader as a context manager
The reader owns an open file. If you stop before the end, for example on an exception or a break, the file stays open until the reader is garbage collected. On Windows, an open file can also block you from deleting or renaming it.
Use a with block to close the file deterministically. Context manager support on the reader has existed since pandas 1.2.
import pandas as pd
with pd.read_csv("demo.csv", chunksize=10_000) as reader:
for chunk in reader:
if chunk["amount"].min() < 30:
print("found a low amount")
break
# The file handle is closed here, even after break or an exception.When a loop runs to the end, the reader closes itself. The with block therefore matters most on early exits and errors, which is where leaks happen.
The following diagram shows the reader's life cycle.
Iterating: for loops, next and enumerate
A for loop is the usual way to consume a reader. It calls next(reader) repeatedly until the reader raises StopIteration. You can call next yourself when you want just the first chunk, for instance to inspect dtypes:
import pandas as pd
with pd.read_csv("demo.csv", chunksize=10_000) as reader:
first = next(reader)
print(first.dtypes)
print(len(first))To process only the first few chunks, use itertools.islice. It stops the loop without a manual break:
from itertools import islice
import pandas as pd
with pd.read_csv("demo.csv", chunksize=10_000) as reader:
for chunk in islice(reader, 2):
print(len(chunk), chunk["amount"].sum().round(2))Use enumerate(reader) when you need the chunk number for logging, progress output, or naming output files.
get_chunk: manual control over how many rows to read
reader.get_chunk(size) returns the next size rows as a DataFrame. If you leave out size, it uses the chunksize you gave to read_csv.
import pandas as pd
reader = pd.read_csv("big.csv", chunksize=50_000)
first_chunk = reader.get_chunk()
next_chunk = reader.get_chunk(1_000)
reader.close()first_chunk has up to 50,000 rows, because that is the default size. next_chunk has up to 1,000 rows, because we overrode it for that single call. The override does not change the default for later calls.
get_chunk is useful when the chunk size is not constant:
- Read a small preview, then decide whether to continue.
- Read a fixed-size header block, then switch to a larger size for the body.
- Pull rows on demand from a function that is called at irregular times.
Mixing get_chunk and a for loop
Both get_chunk and the loop advance the same position. You can mix them freely:
import pandas as pd
with pd.read_csv("demo.csv", chunksize=10_000) as reader:
preview = reader.get_chunk(3) # rows 0-2
block = reader.get_chunk() # rows 3-10002 (10,000 rows)
print(len(preview), len(block))
for chunk in reader: # picks up at row 10003
print(len(chunk))The output is:
3 10000
10000
4997The loop does not start from the top. Rows that get_chunk already returned are gone from the reader's point of view.
Running out of rows
Once the file is exhausted, get_chunk raises StopIteration, just like next. A for loop swallows that exception, but a manual call does not. If you drive the reader by hand, catch it:
import pandas as pd
with pd.read_csv("demo.csv", chunksize=20_000) as reader:
while True:
try:
chunk = reader.get_chunk()
except StopIteration:
break
print(len(chunk))iterator=True: a reader without a fixed chunk size
read_csv also accepts iterator=True. It returns the same kind of reader but sets no default chunk size, so you decide the size on every call:
import pandas as pd
with pd.read_csv("demo.csv", iterator=True) as reader:
small = reader.get_chunk(5)
bigger = reader.get_chunk(5_000)
print(len(small), len(bigger))Always pass an explicit size to get_chunk in this mode, since there is no default to fall back on. Passing chunksize alone already implies iterator behavior, so most code only needs chunksize.
Wrapping a reader in a generator
A reader is single-use and ties up a file handle. If several parts of your program need cleaned chunks, put the reading and cleaning in one generator function. Callers then get a plain iterable and never touch the reader:
import pandas as pd
def iter_clean(path, chunksize=10_000):
with pd.read_csv(path, chunksize=chunksize) as reader:
for chunk in reader:
yield chunk.dropna(subset=["amount"])
total = 0.0
for clean in iter_clean("demo.csv"):
total += clean["amount"].sum()
print(round(total, 2))The with block lives inside the generator. The file closes when the generator finishes, or when it is closed or garbage collected after an early exit.
Choosing between the patterns
| Pattern | Use it when | Watch out for |
|---|---|---|
| `with` plus `for chunk in reader` | Standard processing of the whole file | Nothing special. This is the default choice. |
| `next(reader)` | You need only the first chunk, for example to inspect dtypes | Raises `StopIteration` on an empty file or when no chunks remain |
| `islice(reader, k)` | You want the first `k` chunks for a test run | The reader is left partway through the file |
| `get_chunk(size)` | Chunk sizes vary or are driven by your own logic | Catch `StopIteration` when calling it in a manual loop |
| Generator wrapper | Several consumers share the same cleaning logic | The file stays open until the generator is closed |
Common mistakes with the reader
- Looping twice over one reader. The second loop yields nothing, because the reader is at the end. Create a new reader for a second pass.
- Calling
list(reader). This pulls every chunk into memory at once, which removes the whole benefit of chunking. Only do it on a deliberately small test file. - Forgetting
close()when not usingwith. The file handle stays open after an earlybreakor an exception. - Assuming the last chunk is full-sized. Code that indexes by position, such as
chunk.iloc[9999], fails on a short final chunk. - Treating the index as per-chunk.
chunk.loc[0]works only in the first chunk. Reset the index if your code relies on it.
Exercise
You open reader = pd.read_csv("demo.csv", chunksize=10_000), call reader.get_chunk(100) once, and then run for chunk in reader: print(len(chunk)). The file has 25,000 data rows. What does the loop print, and why?
Show answer
It prints 10000, 10000, 4900. The reader keeps one position. get_chunk(100) consumed the first 100 rows, so the loop starts at row 100 and uses the default chunk size of 10,000. Two full chunks follow, and the remaining 25,000 - 100 - 20,000 = 4,900 rows form the last chunk.
Exercise
Write a function first_rows_over(path, threshold) that returns the first row where amount is greater than threshold, or None if no row qualifies. It must stop reading the file as soon as it finds a match and must not leave the file open.
Show answer
Use a with block and return from inside the loop:
def firstrowsover(path, threshold):
with pd.readcsv(path, chunksize=10000) as reader:
for chunk in reader:
hits = chunk[chunk["amount"] > threshold]
if not hits.empty:
return hits.iloc[0]
return None
Returning inside the with block triggers the context manager's close, so the file is released even though the loop did not finish.