Phase 1: Prepare
Step 1 Warm-up recall
From M6.L2: what type is data read from a file?
Private: nothing you type here is sent or stored.
Step 2 Learning goal
By the end of this lesson you can:
- describe a CSV file (Foundation);
- read rows as dictionaries (Core);
- summarise a column (Core).
Phase 2: Teach
Step 3 A familiar example
A register has a header row naming the columns, then one row per student. Reading by column name is safer than by column number, because the order of columns can change.
Step 4 Clear explanation
A CSV file (comma-separated values) is a table written as text.
import csv
rows = []
with open("scores.csv", newline="") as f:
for row in csv.DictReader(f):
rows.append(row)
total = 0
for r in rows:
total = total + int(r["score"])
print(len(rows), total)
print(rows[0]["name"])2 155
AnnDictReader uses the first line as keys, so each row becomes a dictionary, and the file becomes a list of dictionaries as in Module 4. Values are still text, so convert them. The csv module also copes with commas inside quoted fields, which a plain split cannot.
The same care applies as before: the header must be exactly as written, and a field that has been changed by other software, such as a gene symbol turned into a date, will not match what you expect. Print the first and last rows after reading, to check what you really have.
Step 5 Worked example (4 marks)
A CSV has the header item,qty and the rows pen,3 and ink,2. Find rows[1]["item"] and the total qty.
- DictReader gives two dictionaries. (1 mark)
- rows[1] is the ink row, so item is ink. (1 mark)
- Total qty: 3 + 2 = 5. (1 mark)
- Answer: ink and 5. (1 mark)
Go deeper: the professor's notes
Four digits.
Named columns.
Written down.
Choices
| Choice | Risk |
|---|---|
| two-digit year | confusion after 1999 |
| four-digit year | none of that kind |
At work: A date column
Dates arrive as text.
- Parse each date.
- Print the first and last.
What a careful practitioner decides. Store dates in a form that cannot be misread.
Phase 3: Practise
Step 6 Learner practice (instant-marked)
1. DictReader takes its keys from:
The header row.
2. Each row from DictReader is:
Keys are the column names.
3. Values read from a CSV are:
Convert them.
4. CSV stands for:
A text table.
Phase 4: Close
Step 7 Recap
- CSV is a table in text form with a header line.
- DictReader gives a list of dictionaries.
- Convert fields and check the first and last rows.
Step 8 Exit ticket (ungraded)
Write the code that prints the name of every row with a score over 60.
Private: nothing you type here is sent or stored.
Step 9 Go further (Extension)
Write a program that counts the rows for each value of a column called class.
In industry: Two digits for the year
To save memory, many old programs stored the year as two digits, so 1999 became 99. Estimates of the cost of fixing the Year 2000 problem ranged from about 100 billion US dollars in a 1999 Commerce Department figure to the 300 to 600 billion estimated by Gartner.
Link to this lesson. The way data is written in a file outlives the program that wrote it, so choose clear, complete formats.
Source: Network World (2009); US Senate special committee report, GPO (1999)
Common mistakes
| Mistake | Why it fails |
|---|---|
| Treating fields as numbers | Convert with int or float. |
| Wrong header spelling | Keys must match exactly. |
| Opening without newline="" | Use it with the csv module. |
Limits. Very large files need other tools; this module uses small files that fit in memory.