

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Data Formats
incomplete
2: Parsing JSON
incomplete
3: Variable-Depth JSON
incomplete
4: Fetching JSON
incomplete
5: CSV Files
incomplete
6: CSV Type Conversion
incomplete
7: Filtering CSV Rows
incomplete
8: Writing CSV Files
incomplete
9: Appending to CSV Files
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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 orderwriteheader() writes the first rowwriterows() writes many rowsnewline="" avoids blank-line weirdness on WindowsIf 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.
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.
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.