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

4. Files That Do Work · Build a Reading Report Generator

Summarise a CSV fixture, write a report, and handle a header-only file.

Lesson files · lessons/files-and-formats/reading-report

Before you start
- Read named CSV columns with DictReader.
- Add several values to a running total.
- Write and read text in a temporary directory.

By the end
- Total the minutes and count distinct titles, including titles with zero minutes.
- Write the report to a temporary file and read it back.
- Use the header-only check to explain why both counts can be zero.

Where you can use it
Give a reading club a short report that counts each title once and includes the time from every session.

Combine the CSV reader and file-writing steps from this module. Use one dictionary entry per title and add every row’s minutes to that title. A zero-minute row still adds a title if it is new. A header-only CSV has no data rows, so both totals are zero.

Get the totals working before you write the report. Then use the temporary-folder pattern from the field note to write and read back both summary lines.

Predict
Does Moon Garden count as a title?
- No, because 0 means missing.
- Yes, its minutes happen to be 0.

Worked example (example.py)

minutes = {"Sky Lab": 15, "Moon Garden": 0}
print(len(minutes))
print(sum(minutes.values()))


Example result
2
15

Use the starter fixture. Read sample or empty. Totals must include repeated titles and count a zero-minute title. Write a report with Titles: and Minutes: lines to a temporary file, then print it.

Starter program (starter.py)

import csv
from io import StringIO

data = "title,minutes\nSky Lab,15\nMoon Garden,0\nSky Lab,20\n"
mode = input()
for row in csv.DictReader(StringIO(data)):
    print(row["title"])


Starter input
sample

Hint
Use DictReader and add int(row["minutes"]) to the total for each title. Count keys with len().

Case 1. Try the sample
Input
sample
Expected output
Titles: 2
Minutes: 35

Case 2. Header-only CSV
Input
empty
Expected output
Titles: 0
Minutes: 0

Project checklist
Run the sample case.

Project checklist
Try one different case and explain what happened.

Marking criterion
Program behaviour (4 points)
Each required behaviour works on the supplied cases.

Marking criterion
Use of the lesson concept (3 points)
The code uses the main idea in a clear, purposeful way.

Marking criterion
Test evidence (2 points)
The reflection describes a case, its expected result and what happened.

Marking criterion
Explanation (1 points)
The learner explains a change or design decision in their own words.

Stretch
Generate a JSON summary alongside the text report and compare what each format is good at.

Reflect
How would you tell an empty file from a file with a valid zero-minute record?

Check your prediction
Yes, its minutes happen to be 0. The key is present. Zero is a legitimate reading time.
