

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
click for more info
Not enough gems
Cost: 6 gems
1: Data Formats
incomplete
2: Parsing JSON
incomplete
3: Variable-Depth JSON
incomplete
4: Fetching JSON
incomplete
5: CSV Files
incomplete
6: CSV Type Conversion
incomplete
7: Filtering CSV Rows
incomplete
8: Writing CSV Files
incomplete
9: Appending to CSV Files
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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.
CSV sticks around because it's:
One downside is that CSV has almost no built-in type information. Unlike JSON, everything is text.
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"}
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.
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
SnackStack's device telemetry team exports sensor readings as CSV files. Let's make sure we can parse them.