Sub topic 7
Writing Results to Disk Chunk by Chunk
Filtering a large CSV chunk by chunk is only useful if the result has somewhere to go. If you collect every matching row in a list and call pd.concat at the end, the result must fit in memory. That brings back the problem chunking was meant to avoid. This chapter shows how to append each chunk's output to a file as you go, so memory use stays near the size of one chunk.
Prerequisites
This chapter assumes you know the following:
- Basic Python, including loops and context managers (
with). - pandas DataFrames,
read_csv, and boolean filtering. - How
chunksizeturnsread_csvinto an iterator of DataFrames, covered in earlier chapters.
Why not collect everything first?
The previous chapter collected filtered chunks in a list. That works when the filter is selective and the matches are small. It fails when the output is large, for example when you clean a 40 GB file and keep 90% of its rows.
Writing incrementally has three advantages:
- Peak memory stays near one chunk, whatever the output size.
- Partial output exists on disk if the job fails late.
- You can feed the output to another tool while it grows, or stop early.
The cost is that you now manage file state yourself. You must create the file on the first chunk, append to it afterward, and handle the header correctly.
The core pattern: write the first chunk, append the rest
DataFrame.to_csv takes two arguments that control this:
mode:"w"truncates the file and writes from the start."a"appends to the end.header:Truewrites the column names.Falseomits them.
The first chunk must use mode="w" with header=True. Every later chunk must use mode="a" with header=False. If you append the header on every chunk, the column names repeat as data rows in the middle of the file.
import pandas as pd
first = True
with pd.read_csv("events.csv", chunksize=100_000) as reader:
for chunk in reader:
errors = chunk[chunk["status"] == "error"]
errors.to_csv(
"errors.csv",
mode="w" if first else "a",
header=first,
index=False,
)
first = FalseHere is what each part does:
firstis a flag that isTrueonly for the first chunk.mode="w" if first else "a"truncates any olderrors.csvonce, then appends.header=firstwrites column names only once.index=Falsestops pandas from writing the row index as an extra column. Each chunk has its own index (a continuation of the row numbers, such as 100000 to 199999), so writing it would add a meaningless first column.first = Falseruns for every chunk, including the first, so the flag flips after the first write.
The with block closes the reader when the loop ends, even if an exception occurs.
The empty first chunk problem
If the first chunk has no matching rows, errors is an empty DataFrame. to_csv still writes the header for it, which is what you want. The file is created with column names and no rows, and later chunks append to it.
Because the flag flips on every iteration, an empty first chunk causes no trouble. A common mistake is to flip the flag only when rows are written. Then the header is written again by a later chunk. Keep the flag update unconditional.
If no chunk matches at all, the output is a file with just a header. Check whether that is acceptable for whatever reads the file next.
Alternative: write with an open file handle
Instead of passing a path and a mode each time, you can open the output file once and pass the handle to to_csv. This avoids reopening the file for every chunk.
import pandas as pd
with open("errors.csv", "w", newline="") as out, \
pd.read_csv("events.csv", chunksize=100_000) as reader:
for i, chunk in enumerate(reader):
errors = chunk[chunk["status"] == "error"]
errors.to_csv(out, header=(i == 0), index=False)Details worth knowing:
newline=""prevents Python from translating line endings, so pandas controls them. Without it, Windows can produce blank lines between rows.enumerategives the chunk number, soi == 0identifies the first chunk without a separate flag.- Opening with
"w"once at the start truncates any old file, so you don't need amodeargument. - One
withstatement opens both resources. Both close on exit.
The two approaches give the same result. The handle version does less file opening. The path version is easier to read and is easy to adapt when you write to several files.
Transforming as you write
Output chunks don't have to be plain filtered rows. You can clean, convert, or add columns before writing. The pattern stays the same.
import pandas as pd
with open("clean.csv", "w", newline="") as out, \
pd.read_csv(
"events.csv",
chunksize=100_000,
usecols=["id", "timestamp", "status", "amount"],
parse_dates=["timestamp"],
) as reader:
for i, chunk in enumerate(reader):
chunk = chunk.dropna(subset=["amount"])
chunk["amount_cents"] = (chunk["amount"] * 100).round().astype("int64")
chunk = chunk.drop(columns=["amount"])
chunk.to_csv(out, header=(i == 0), index=False)This reads four columns, parses the timestamps, drops rows with a missing amount, converts the amount to integer cents, and writes the result. Memory stays bounded because each chunk is transformed and written before the next one is read.
One restriction applies. Each chunk must be transformable on its own. Operations that need the whole dataset, such as sorting globally, removing duplicates across chunks, or ranking, give wrong results when applied per chunk. The pitfalls chapter covers these.
How the data flows
The diagram shows the loop. Only one chunk and its filtered version exist in memory at a time.
Writing to other formats
CSV is easy to append to because it is plain text with one row per line. Other formats differ.
Parquet
A Parquet file has a footer that is written when the file is closed, so you cannot append to an existing file with to_parquet. Two options work well:
- Write one Parquet file per chunk into a directory, then read the directory later.
- Use
pyarrow.parquet.ParquetWriterto write many batches into one file.
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
writer = None
try:
with pd.read_csv("events.csv", chunksize=100_000) as reader:
for chunk in reader:
table = pa.Table.from_pandas(chunk, preserve_index=False)
if writer is None:
writer = pq.ParquetWriter("events.parquet", table.schema)
writer.write_table(table)
finally:
if writer is not None:
writer.close()The writer takes its schema from the first chunk. Every later chunk must match that schema exactly. If a column's dtype differs between chunks, write_table raises an error. For example, a column that is all integers in the first chunk and has missing values in a later one becomes float. Set dtype in read_csv to prevent this.
Closing the writer in finally matters. An unclosed Parquet file has no footer and cannot be read.
SQL databases
DataFrame.to_sql supports appending directly with if_exists="append". Creating the table with the first chunk and appending afterward follows the same idea as the CSV pattern.
import sqlite3
import pandas as pd
conn = sqlite3.connect("events.db")
try:
with pd.read_csv("events.csv", chunksize=100_000) as reader:
for chunk in reader:
chunk.to_sql("events", conn, if_exists="append", index=False)
finally:
conn.close()With if_exists="append", rerunning the script adds the rows again. Use if_exists="replace" for the first chunk, or drop the table before the loop, if you want reruns to start clean.
Safe output: avoid half-written files
If the job crashes halfway, the output file holds a partial result. A later step might read it and treat it as complete. Write to a temporary name, then rename when the loop finishes.
import os
import pandas as pd
final_path = "errors.csv"
tmp_path = final_path + ".tmp"
with open(tmp_path, "w", newline="") as out, \
pd.read_csv("events.csv", chunksize=100_000) as reader:
for i, chunk in enumerate(reader):
chunk[chunk["status"] == "error"].to_csv(out, header=(i == 0), index=False)
os.replace(tmp_path, final_path)os.replace renames the file in one step on the same filesystem. If the loop fails, the exception stops the script before the rename, so errors.csv is either the old complete version or absent. It never holds a half-written one.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Header lines appear in the middle of the output | `header=True` on every chunk | Use `header=first` or `header=(i == 0)` |
| Output has no header | `header=False` on the first chunk too | Write the header on the first chunk |
| Output contains only the last chunk | `mode="w"` on every chunk | Use `"a"` after the first chunk |
| Extra unnamed first column | Index was written | Pass `index=False` |
| Rerun doubles the rows | Old file was appended to | Start with `mode="w"` on the first chunk |
| Blank lines between rows on Windows | File opened without `newline=""` | Open with `newline=""` |
| Parquet write raises a schema error | dtypes changed between chunks | Fix `dtype` in `read_csv` |
Checking the result
After a chunked write, verify the output instead of assuming it is right. A cheap check is to count rows in the output and compare with a count made during the loop.
import pandas as pd
written = 0
with open("errors.csv", "w", newline="") as out, \
pd.read_csv("events.csv", chunksize=100_000) as reader:
for i, chunk in enumerate(reader):
errors = chunk[chunk["status"] == "error"]
errors.to_csv(out, header=(i == 0), index=False)
written += len(errors)
check = sum(len(c) for c in pd.read_csv("errors.csv", chunksize=100_000))
print(written, check, written == check)The check reads the output in chunks too, so it also fits in memory. If the counts differ, look for embedded newlines in quoted fields or a header written more than once.
Key points
- Write the first chunk with
mode="w"and a header, then append the rest withmode="a"and no header. - Pass
index=Falseunless you need the index. - Update the first-chunk flag unconditionally, so an empty first chunk causes no problems.
- Parquet cannot be appended with
to_parquet. Use per-chunk files orParquetWriter. - Write to a temporary file and rename it to avoid leaving partial output.
Exercise
A script writes each filtered chunk with chunk.to_csv("out.csv", mode="a", index=False). The first run produces a correct file, but a second run produces a file with double the rows, and the header line appears only once at the top of the first run's data. What are the two problems, and how do you fix both?
Show answer
First, mode="a" on the first chunk never truncates the old file, so a rerun appends to the previous output. Second, header is left at its default of True, so the header is written again for every chunk, including in the middle of the file. The file the learner inspects after the first run may still look right only if out.csv did not exist before. The fix is to track the first chunk, for example first = True, and use mode="w" if first else "a" and header=first, with first = False at the end of each iteration. Alternatively, open the file once with "w" and pass the handle to to_csv.
Exercise
You convert a large CSV to a single Parquet file with ParquetWriter. The first chunk has an age column of integers, but a later chunk has missing ages, so pandas reads that column as float and write_table fails. Give two ways to fix this.
Show answer
Set the dtype explicitly when reading so it is the same in every chunk, for example dtype={"age": "Int64"} using pandas' nullable integer type. Alternatively, cast each chunk to a fixed schema before converting, for example chunk["age"] = chunk["age"].astype("Int64"), or pass an explicit schema to ParquetWriter and build each table with pa.Table.from_pandas(chunk, schema=schema).