Reading a CSV File

The csv module turns a file of text into rows you can work with.

Why not just split on commas

Because a field can contain a comma inside quotes, and splitting breaks the row in the wrong place. csv knows the rules; a split does not.

import csv

with open("scores.csv") as f:
    for row in csv.reader(f):
        print(row)

DictReader gives you named rows

It reads the header line and hands back a dictionary per row, which is exactly the shape the last lesson argued for. Every value arrives as a string -- that is the next lesson.

import csv

with open("scores.csv") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["score"])

Exercise

Try It Yourself

A file scores.csv is supplied when your work is checked, with a name and a score column. Print each name and score on its own line, separated by a space. Pressing Run on its own reports a FileNotFoundError, so use Check my work.

Press Run to see output

Check Your Understanding