Sub topic 4
Working with the chunk reader: with, iterator and get_chunk
This chapter assumes you know basic Python loops and context managers, and that you have used pandas.read_csv before. It also assumes you have seen chunksize in the previous chapter. Here you will look at the object that read_csv returns when you pass chunksize, and at three ways to work with it.
What the reader is
With chunksize, read_csv does not return a DataFrame. It returns a TextFileReader, which I will call the reader. The reader keeps the file open and parses rows only when you ask for them. Each request gives you a DataFrame of up to chunksize rows. The last chunk may be smaller.
Because the reader holds an open file, you have two jobs: consume it correctly and close it when you finish.
Using with (recommended)
The reader is a context manager. Leaving the with block closes the file, even if your code raises an error.
import pandas as pd
total_rows = 0
with pd.read_csv("big.csv", chunksize=100_000) as reader:
for chunk in reader:
total_rows += len(chunk)
print(total_rows)Use this form by default. The file handle is released as soon as the block ends, which matters on Windows, where an open file cannot be deleted or replaced.
Using the reader as an iterator
The reader is also an iterator. You can loop over it directly, as in the first example of the previous chapter, or step through it with next.
import pandas as pd
with pd.read_csv("big.csv", chunksize=100_000) as reader:
first = next(reader)
print(first.shape)
for chunk in reader:
print(chunk.shape)The for loop continues where next stopped, because both use the same position in the file. An iterator can be consumed only once. After the loop ends, the reader is exhausted, and another for loop over it yields nothing. To make a second pass, call read_csv again.
A bare for chunk in pd.read_csv(..., chunksize=...) also works. Pandas closes the file when the iteration reaches the end. If you stop early with break or an exception, the file stays open until the reader is garbage collected, so prefer with.
Using get_chunk
get_chunk returns the next chunk on demand. You can pass a different row count for that call.
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()The first call returns 50,000 rows, which is the chunksize. The second returns 1,000 rows, and the position moves forward by that amount. Use get_chunk when you do not want a loop, for example to peek at the first rows, or to read a header block of one size and the body in larger pieces. When the file has no more rows, get_chunk raises StopIteration.
Here the reader is not in a with block, so you must call close() yourself. contextlib.closing(reader) is an alternative if you prefer a block.
Choosing between the three
| Approach | Best for | Closes the file for you |
|---|---|---|
| `with ... as reader` plus `for` | Most processing loops | Yes, on leaving the block |
| `next(reader)` or bare `for` | Short scripts, peeking at one chunk | Only at the end of iteration |
| `reader.get_chunk(n)` | Variable chunk sizes, manual control | No, call `close()` |
Common mistakes
- Looping over the same reader twice. The second loop is empty. Reopen the file instead.
- Calling
list(reader)orpd.concat(reader). This loads every chunk and defeats the purpose. Later chapters show whenconcatis safe, which is after you have filtered or reduced each chunk. - Forgetting that the reader keeps state. If you call
nextfor a peek, that chunk is consumed and is not repeated in the loop.
Exercise
You run with pd.read_csv("big.csv", chunksize=10_000) as reader: and call next(reader) once to inspect the first chunk. Then you loop for chunk in reader: and sum len(chunk). Does the sum include the first 10,000 rows? How would you include them?
Show answer
No. next(reader) consumed the first chunk, and the loop starts at the second one. To include those rows, add len(first) to the total, or process the first chunk with the same function before the loop. Alternatively, peek with a separate pd.read_csv("big.csv", nrows=10_000) call and leave the reader untouched.