MSIT

A file that stays

grades.csv is data. The lesson keeps it, so an edit cannot replace those rows. report.py is the program. It should open the csv file and return the average score.

The csv module reads the rows. csv.DictReader uses the first line as the field names. The csv documentation describes that reader. You do not need a third-party package. csv is part of Python.

A file name in the cell is a single segment, such as report.py or grades.csv.

Code and data stay apart

Code can change while you work. Kept data should not.

  • report.py is the entry file. You write average there.
  • grades.csv is kept. The header is name,score. The rows are Ada with 10 and Bea with 30.

The average of 10 and 30 is 20. That is the number average must return for this file. If the rows changed, the average would change. Because the csv file stays, the check can expect the same result every time.

A worked example

DictReader yields one dictionary per data row. The keys are the header names, so row["score"] is the score as text. Convert each score with int before you add.

  1. Import csv.
  2. Open grades.csv with encoding="utf-8".
  3. Read each row and collect the scores.
  4. Return the sum divided by the number of scores.

with closes the file when the block ends. For Ada 10 and Bea 30, scores is [10, 30], the sum is 40, and 40 divided by 2 is 20. Division with / yields a float, and 20.0 still compares equal to 20.

The csv module implements classes to read and write tabular data in CSV format.

— Python documentation, csv

Match the file with its job.

  • greetings.py
  • grades.csv

row["score"] is text until you convert it. Add numbers, not strings.

Exercise

Write average in report.py. It reads grades.csv and returns the average of the score column. Leave the csv file as the lesson wrote it.

Write average in report.py. It reads grades.csv and returns the average of the score column.

Output