×

python · level 2 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A file is a table saved as text, one per line.

Spreadsheets save tables as CSV: one row per line, with commas between the columns. The first row is often a naming each column. Python's csv module writes and reads these files for you.

csv.writer(file) makes a writer, and .writerow(["Rex", 4]) writes one row from a list. csv.reader(file) hands the rows back as lists, one per line.

Open CSV files with newline="", so line endings work the same on every computer. Every value comes back as a string, so convert numbers yourself.

import csv
with open("pets.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["name", "age"])
    writer.writerow(["Rex", 4])
    writer.writerow(["Mog", 11])
with open("pets.csv", newline="") as file:
    for row in csv.reader(file):
        print(row)

A value with a comma inside, like "Smith, Jo", is wrapped in quotes so it stays in one column.