We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Writing CSV Files

Once you've read a CSV, you'll usually process it somehow, then write the result back out in CSV.

The csv.DictWriter class writes a dictionary to a CSV file. Give it the output columns, write the header, then write rows:

def save_attendance(filename: str, attendees: list[dict[str, str]]) -> None:
    fieldnames = ["name", "role", "checked_in"]

    with open(filename, "w", newline="") as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(attendees)
  • fieldnames decides the column order
  • writeheader() writes the first row
  • writerows() writes many rows
  • newline="" avoids blank-line weirdness on Windows

If you're generating results incrementally, the writerow() function can be used to write one row at a time in a loop:

for attendee in attendees:
    writer.writerow(attendee)

For large datasets, it's more memory-efficient to work with files (both reading and writing) by streaming rows instead of first collecting them in a list. Do you really want to load a 20GB CSV directly into RAM? Probably not.

Streaming Row by Row

This example opens both an input and output file, then reads, processes, and writes one row at a time:

def stream_inventory_flags(input_file: str, output_file: str) -> None:
    with (
        open(input_file, "r", newline="") as in_f,
        open(output_file, "w", newline="") as out_f,
    ):
        reader = csv.DictReader(in_f)
        writer = csv.DictWriter(out_f, fieldnames=["sku", "needs_restock"])
        writer.writeheader()

        for row in reader:
            writer.writerow(
                {
                    "sku": row["sku"],
                    "needs_restock": int(row["quantity"]) < int(row["reorder_at"]),
                }
            )

This can handle suuuuper large files. You're no longer limited by RAM, just by disk space.

Assignment

Complete the export_temperature_summary function. It accepts a list of device dictionaries and writes a CSV at the provided path, with only device_id and temperature.