Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Files with a future
EXPERIMENT 30 / 101

Rows with a proper passport.

Read named columns, validate numbers, and write CSV without hand-splitting commas.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

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.

csv_records.py
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}")
↳ EXPECTED OUTPUT
Total: 60

03 Under the hood

  1. 1

    newline="" lets the csv module manage line endings correctly. A consistent encoding avoids machine-dependent text decoding.

  2. 2

    DictWriter quotes the comma inside the first task name. A manual split(",") would incorrectly treat that comma as a column boundary.

  3. 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

A SMALL MISSION

Import two task rows and export only rows with minutes at least 30.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

What type does DictReader produce for a numeric field?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.