Rows with a proper passport.
Read named columns, validate numbers, and write CSV without hand-splitting commas.
01 The idea
CSV is a structured text format, not simply a string split on commas. Fields can contain commas, quotes, and line breaks. DictReader maps header names to string values; DictWriter writes records with a declared column order. Validate the shape and convert types at the input boundary so the rest of your program can use reliable data.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
import csv
from pathlib import Path
path = Path("tasks.csv")
with path.open("w", newline="", encoding="utf-8") as stream:
writer = csv.DictWriter(stream, fieldnames=["name", "minutes"])
writer.writeheader()
writer.writerows([{"name": "Build, carefully", "minutes": 40}, {"name": "Test", "minutes": 20}])
with path.open(newline="", encoding="utf-8") as stream:
rows = csv.DictReader(stream)
total = sum(int(row["minutes"]) for row in rows)
print(f"Total: {total}")Total: 60
03 Under the hood
- 1
newline="" lets the csv module manage line endings correctly. A consistent encoding avoids machine-dependent text decoding.
- 2
DictWriter quotes the comma inside the first task name. A manual split(",") would incorrectly treat that comma as a column boundary.
- 3
DictReader returns field values as strings. Real imports should verify required headers and report the source row number when numeric conversion fails.
04 Your turn, builder
Import two task rows and export only rows with minutes at least 30.
Reveal one possible solution +
import csv, io
source = io.StringIO("name,minutes\nBuild,40\nTest,20\n")
rows = [row for row in csv.DictReader(source) if int(row["minutes"]) >= 30]
print([row["name"] for row in rows])05 Check your signal
What type does DictReader produce for a numeric field?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.