Module 08 · Lesson 04
CSV Files: Reading and Writing Tables
Handle spreadsheet-style data: read CSV rows with csv.reader and DictReader, convert their text to numbers, and write tables back out with csv.writer and DictWriter.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Read rows as lists
- Rows as dictionaries
- Write a table
- Watch the warmest city win
Tables as text
A CSV file is a table saved as plain text: one row per line, values split by commas.
The format
name,scoreon the first line is the header. Each line after it is one row.reader
csv.reader(f)gives each row as a list of strings.DictReader
csv.DictReader(f)gives each row as a dictionary keyed by the header.writer
csv.writer(f).writerow([...])writes a row. Open the file withnewline="".
Tables everywhere
CSV is the simplest way to move a table from one program to another.
- SpreadsheetsExcel and Google Sheets can save and open CSV files.
- Bank statementsMost banks let you download your spending as a CSV.
- Sports statsMatch results and player scores are often shared as CSV tables.
- Data setsMost data you can download for projects starts life as a CSV.
Looping over rows
This line reads a table one row at a time. Tap each part to see its job.
Part 1 of 5
loop:One pass of the loop for each data row.
Read and write tables
Pick an example, change it, then press Run. Say what you expect to see before you press. Each Run starts with no files, so every example writes its own.
Example 1 of 6Read rows
csv.reader turns each line into a list of strings.
Your turn: Skip the header row by calling next() on the reader before the loop.
import csv
with open("pets.csv", "w", encoding="utf-8", newline="") as f:
f.write("name,kind,age\nRex,dog,4\nTom,cat,2\n")
with open("pets.csv", encoding="utf-8", newline="") as f:
for row in csv.reader(f):
print(row)Press Run to see what it prints.Watch the warmest city win
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- import csv
- lines = ["city,temp", "Oslo,3", "Rome,18"]
- warmest = None
- for row in csv.DictReader(lines):
- temp = int(row["temp"])
- if warmest is None or temp > warmest[1]:
- warmest = (row["city"], temp)
- print(warmest)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.A row with an empty value:
import csv
print(next(csv.reader(["a,,c"])))0 of 6 answered
Common CSV misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
import csv
with open("in.csv", newline="", encoding="utf-8") as f:
reader = csv.reader(f) # rows as lists of strings
header = next(reader)
for row in reader: ...
with open("in.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f): # rows as dictionaries
row["price"]
with open("out.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
w = csv.DictWriter(f, fieldnames=["a", "b"])
w.writeheader(); w.writerows(dicts)
csv.reader(f, delimiter=";")Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Totals from a sales export
A shop exports its sales as CSV. Work out the total revenue and the revenue per product, printing products in alphabetical order.
import csv
with open("sales.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows([
["product", "qty", "price"],
["mug", "3", "6.50"],
["lamp", "1", "24.00"],
["mug", "2", "6.50"],
["candle", "4", "3.25"],
])
revenue = {}
with open("sales.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
amount = int(row["qty"]) * float(row["price"])
revenue[row["product"]] = revenue.get(row["product"], 0) + amount
for product in sorted(revenue):
print(f"{product}: {revenue[product]:.2f}")
print(f"Total: {sum(revenue.values()):.2f}")Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Adding numbers that are still text
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
row = {"qty": "2", "price": "3"}
print(row["qty"] * row["price"])Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Personal finance
Converting a bank statement
A budgeting app imports bank statements that use semicolons as separators. It reads them, sorts spending into categories and writes a clean summary CSV for the user.
Why Python fits
delimiter=";"reads the semicolon file. Negative amounts are spending, so they are turned positive and added per shop.sorted(spent.items())gives (shop, amount) tuples in order, whichwriterowswrites directly.Pythonimport csv with open("statement.csv", "w", newline="", encoding="utf-8") as f: f.write("date;shop;amount\n03-01;Grocer;-23.40\n03-02;Salary;1500.00\n03-02;Cafe;-4.20\n03-04;Grocer;-31.10\n") spent = {} with open("statement.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f, delimiter=";"): amount = float(row["amount"]) if amount < 0: spent[row["shop"]] = round(spent.get(row["shop"], 0) - amount, 2) with open("summary.csv", "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerow(["shop", "spent"]) writer.writerows(sorted(spent.items())) with open("summary.csv", newline="", encoding="utf-8") as f: for row in csv.reader(f): print(row)OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Why does my file have blank lines between rows on Windows?
Can I open the CSV in a spreadsheet afterwards?
What if some rows have missing values?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 13 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.