Contact
Evil Genius SocietyHomeLearnForumLeaderboardSocialsMessages
← Back to module

Lesson 3 of 9

CSV — comma-separated values — is the plainest way to store a table. Each line is a row, commas separate the columns. Every spreadsheet program reads and writes it.

name,age,city
Ada,36,London
Grace,45,New York

A quick preview: import

CSV support lives in a module — a bundle of ready-made code that ships with Python. You get at it with import:

import csv

That one line makes everything in the csv module available as csv.something. Module 7 covers imports properly; for now, just put import csv at the top and use it.

Why not just .split(",")?

You could parse CSV by hand:

line = "Ada,36,London"
print(line.split(","))

That works until a value contains a comma — "Smith, Ada",36,London breaks it completely. The csv module handles quoting, embedded commas, and newlines correctly. Use it.

Writing a CSV

import csv

rows = [
    ["name", "age", "city"],
    ["Ada", 36, "London"],
    ["Grace", 45, "New York"],
]

with open("people.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

with open("people.csv") as f:
    print(f.read().strip())

newline="" is required when writing CSV — without it you can get blank lines between rows on some systems. .writerow() writes one row; .writerows() writes a list of them.

Reading a CSV

import csv

with open("people.csv", "w", newline="") as f:
    csv.writer(f).writerows([["name", "age"], ["Ada", 36], ["Grace", 45]])

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

Every row comes back as a list of strings — note '36', not 36. CSV has no types. Convert what you need:

import csv

with open("people.csv", "w", newline="") as f:
    csv.writer(f).writerows([["name", "age"], ["Ada", 36], ["Grace", 45]])

total = 0
with open("people.csv") as f:
    reader = csv.reader(f)
    next(reader)
    for row in reader:
        total += int(row[1])

print(total)

next(reader) reads and discards one row — here, the header.

DictReader and DictWriter

Working with row[1] is brittle; add a column and every index shifts. DictReader uses the header row to give you a dictionary per row:

import csv

with open("people.csv", "w", newline="") as f:
    csv.writer(f).writerows([["name", "age"], ["Ada", 36], ["Grace", 45]])

with open("people.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"{row['name']} is {row['age']}")

row["name"] says what it means and survives column reordering. DictWriter is the mirror image:

import csv

people = [
    {"name": "Ada", "age": 36},
    {"name": "Grace", "age": 45},
]

with open("people.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "age"])
    writer.writeheader()
    writer.writerows(people)

with open("people.csv") as f:
    print(f.read().strip())

fieldnames sets the column order, and .writeheader() writes that first row.

Try it yourself

Write three people to a CSV, then read them back with DictReader and total their ages.

Checkpoint

  • import csv brings in Python's CSV support — don't hand-roll it with .split(",").
  • Always pass newline="" when opening a file for CSV writing.
  • csv.reader gives lists of strings; everything is text, so convert types yourself.
  • DictReader/DictWriter use the header row, so you index by name instead of number.

Questions about this lesson

Log in to ask a question.