We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

CSV Files

CSV is the default "just export it to a file" data format.

It's simple, everywhere, and kind of dumb. That's not an insult; dumb formats are useful formats because everyone understands them.

If you do a lot of work with non-technical stakeholders, you'll work with CSVs via Microsoft Excel or Google Sheets constantly.

This is what CSV data looks like:

title,author,year
Dune,Frank Herbert,1965
The Hobbit,J.R.R. Tolkien,1937
Neuromancer,William Gibson,1984

Each line is a row, and rows are separated by newlines. Fields are separated by commas.

The first row usually contains column names.

Why CSV Is So Common

CSV sticks around because it's:

  • Easy to export
  • Easy to share
  • Easy to open in any spreadsheet software
  • Easy to parse in almost any programming language

One downside is that CSV has almost no built-in type information. Unlike JSON, everything is text.

Reading a CSV File

Python's built-in csv module can parse CSV files using csv.DictReader:

import csv

with open("books.csv", "r", newline="") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)

Each row comes back as a dictionary:

{"title": "Dune", "author": "Frank Herbert", "year": "1965"}

Working With Open Files

csv.DictReader expects a file-like object: something it can read text from one line at a time.

When you call open(), Python gives you a file object. DictReader reads from that and parses each CSV row as a dictionary.

Always use a with statement when opening files. It closes the file automatically, even if something goes wrong. I also recommend setting newline="" when opening CSV files. This lets the csv module handle newlines itself, which avoids weird blank-line behavior on some systems.

Loading Rows Into a List

If you want the whole file in memory, you can build a list of dictionaries, one for each row:

def load_book_data(filename: str) -> list[dict]:
    books = []
    with open(filename, "r", newline="") as file:
        reader = csv.DictReader(file)
        for row in reader:
            books.append(row)
    return books

Assignment

SnackStack's device telemetry team exports sensor readings as CSV files. Let's make sure we can parse them.