Capstone · Ship a Study Tracker CLI
Read a real path, validate every CSV row, and test success and failure.
Jump to the automation labBuild on the report you wrote in the previous lesson. Split the program into read_totals(path) for reading and validation, format_report(totals) for formatting, and main(argv, emit) for the command-line interface. Keeping output behind emit lets a test capture it without editing the program.
The CSV header must be topic,minutes. Each row must have exactly two fields. Normalize topic names to lowercase and require them to match TOPIC. Minutes must be a positive integer. Raise ValueError for malformed input and include the CSV line number for problems in a data row.
A correct run prints the alphabetical report and returns 0. A missing file or invalid CSV produces an error and returns 2. Before running the program on your own study log, verify a valid file, a header-only file, a missing file, and invalid rows. The example below shows how to run an importable version from a terminal.
Check the header and parse each data row.
Worked examples
Run and test the saved command
Save the functions in study_tracker.py and replace the browser demo with this entry point. Save the sample CSV as study.csv beside it. The pytest test checks the real file reader using a temporary path.
if __name__ == "__main__":
import sys
sys.exit(main(sys.argv[1:]))topic,minutes
Python,25
math,30
python,20from study_tracker import main
def test_report(tmp_path):
path = tmp_path / "study.csv"
path.write_text("topic,minutes\nCode,2\ncode,4\n", encoding="utf-8")
messages = []
assert main([str(path)], emit=messages.append) == 0
assert messages == ["code: 6 min\nTotal: 6 min"]python study_tracker.py study.csv
python -m pytest -qRun the example and practice
Complete read_totals to enforce the data rules above. Preserve the sample report. Check your program against invalid rows and a missing file, then run Check output for the additional cases.
Target output
math: 30 min
python: 45 min
Total: 75 minShow a hint
DictReader uses the key None for extra fields and the value None for missing ones. Wrap per-row validation in try/except to add rows.line_num. main already catches the resulting ValueError.
Ready
Run your code to see the output here.
Check output also tests your code with additional cases.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
import argparse
import csv
import re
from pathlib import Path
from tempfile import TemporaryDirectory
TOPIC = re.compile(r"[a-z][a-z0-9 -]*")
def read_totals(path):
totals = {}
with path.open(encoding="utf-8", newline="") as file:
rows = csv.DictReader(file)
if rows.fieldnames != ["topic", "minutes"]:
raise ValueError("expected a topic,minutes header")
for row in rows:
try:
if None in row or row["topic"] is None or row["minutes"] is None:
raise ValueError("expected two fields")
topic = row["topic"].strip().lower()
minutes = int(row["minutes"])
if TOPIC.fullmatch(topic) is None:
raise ValueError("invalid topic")
if minutes <= 0:
raise ValueError("minutes must be positive")
except ValueError as error:
raise ValueError(f"line {rows.line_num}: {error}") from error
totals[topic] = totals.get(topic, 0) + minutes
return totals
def format_report(totals):
lines = [f"{topic}: {totals[topic]} min" for topic in sorted(totals)]
lines.append(f"Total: {sum(totals.values())} min")
return "\n".join(lines)
def main(argv, emit=print):
parser = argparse.ArgumentParser(description="Summarize a study log.")
parser.add_argument("log", type=Path)
args = parser.parse_args(argv)
try:
totals = read_totals(args.log)
except (OSError, ValueError) as error:
emit(f"Could not read log: {error}")
return 2
emit(format_report(totals))
return 0
with TemporaryDirectory() as directory:
path = Path(directory) / "study.csv"
path.write_text("topic,minutes\nPython,25\n math ,30\npython,20\n", encoding="utf-8")
assert main([str(path)]) == 0Automation lab
Preview a batch of file moves
Build a command that reads sample paths and reports a destination for each supported file type before anyone moves files.
Ready
Run the example to see the output here.
Add two files from separate folders with the same name. Extend the preview to flag that destination collision.
Further reading in Automate the Boring Stuff with Python by Al Sweigart