← All lessons

CSV: a table in a file

Sign in · Sign up

Lesson 9.5

CSV is lines with a separator, handy for tables. The csv module reads and writes them properly:

import csv

with open("scores.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Score"])
    writer.writerow(["Mia", ...])        # you fill the score in yourself

with open("scores.csv", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

writerow takes a list — one row of the table. reader gives the rows out as lists too. newline="" is required when writing: without it blank lines appear between the rows.

The check sets the file name filename, the header header and the rows rows — a list of "name, score" pairs. Write the table with csv.writer, read it with csv.reader and print each row with print — that's how the list gets printed.

Hint

Writing and reading are two different with blocks.

In csv.writer write the header first, then each pair from rows in a loop, one line each. When reading, csv.reader gives lists — print those. newline="" is needed in both blocks, otherwise blank lines appear.