──────────────────────────────────────

2. Files That Do Work · Read a Spreadsheet Export

Read CSV using column names and convert a numeric field.

Lesson files · lessons/files-and-formats/csv-records

Before you start
- Look up a value by its dictionary key.
- Convert number text with int() and keep a running total in a loop.

By the end
- Read the minutes by column name, even when the columns change order.
- Predict the total for a header-only CSV.
- Explain why a comma inside a quoted title stays in that title.

Where you can use it
Total time from a club’s spreadsheet export by reading the minutes column by name, even after someone rearranges the columns.

CSV represents a table as text. DictReader uses the header row to name the columns and gives you one dictionary per data row. It keeps quoted text like "Map, Revised" in one field. Row values arrive as text, so convert minutes with int() before adding them.

The example uses StringIO to let DictReader read a string as if it were a file. The starter uses sys.stdin, which lets the same reader take all the CSV lines from Program input. Both give you rows to use in a for loop.

Predict
How many fields are in "Map, Revised",12?
- Three.
- Two.

Worked example (example.py)

import csv
from io import StringIO

data = 'name,minutes\n"Map, Revised",12\n'
for row in csv.DictReader(StringIO(data)):
    print(row["name"])
    print(int(row["minutes"]) + 3)


Example result
Map, Revised
15

Use DictReader to total the minutes from the CSV in Program input. Print Minutes: followed by the total. The first line names the columns. Handle any number of data rows, including zero.

Starter program (starter.py)

import csv
import sys

# sys.stdin gives DictReader the input lines as one stream.
for row in csv.DictReader(sys.stdin):
    print(row["name"])


Starter input
name,minutes
"Map, Revised",12
Comet,8

Hint
Start total at 0. Add int(row["minutes"]) for each row, then print once after the loop.

Case 1. Try the sample
Input
name,minutes
"Map, Revised",12
Comet,8
Expected output
Minutes: 20

Case 2. Columns in a different order
Input
minutes,name
7,Comet
3,"Moon, Blue"
Expected output
Minutes: 10

Case 3. Header only
Input
name,minutes
Expected output
Minutes: 0

Stretch
Add a third title with zero minutes and explain what stays the same. In a terminal, use the CSV input file or finish typing with Ctrl+D on macOS or Linux, or Ctrl+Z followed by Enter on Windows.

Reflect
What is the type of row["minutes"] before int runs?

Check your prediction
Two. The quotes mark the comma inside the title as part of the field.
