Python theorytheory 0/50 · 0%
Tooling · medium

35. Working with CSV and structured text

Reading/writing tabular data with the csv module.

The `csv` module reads and writes comma-separated (or other delimiter) tabular data safely, handling quoting edge cases that naive `.split(",")` would get wrong.

python
import csv
import io

text = "address,balance\n0xabc,5\n0xdef,3"
reader = csv.DictReader(io.StringIO(text))
rows = list(reader)   # [{"address": "0xabc", "balance": "5"}, ...]

output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=["address", "balance"])
writer.writeheader()
writer.writerow({"address": "0xabc", "balance": 5})

All values from `csv.reader`/`DictReader` are strings; convert numeric columns explicitly with `int()`/`float()`.

Check your understanding

  1. 1. What type are values read by csv.DictReader?

  2. 2. Why use the csv module instead of `.split(",")`?

  3. 3. What does `csv.DictReader` return per row?