python · level 2 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Numbers out of a CSV. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import csv
with open("sales.csv", "w", newline="") as file:
csv.writer(file).writerow(["Mon", 40, 25])
with open("sales.csv", newline="") as file:
for day, cakes, pies in csv.reader(file):
print(cakes + pies)
your turn
Your turn. Log your workouts.
Fill in the method that writes one row, twice. Each row is an activity and the whole minutes it took, so pick two of your own.
fix it
Ali got 77 out of 20? Can you fix it?
- What type is
markwhen it comes out of the reader? - Every CSV value is a string, and a string times 2 repeats itself:
"7" * 2is"77". - Change mark * 2 to int(mark) * 2 on line 10, then run.
nailed it
you saved a real table. :D
csv.writer(file).writerow(list)writes one row.csv.reader(file)hands back each row as a list of strings.- Open CSV files with
newline=""and convert numbers yourself.
new words in your collection
- CSV
- row
- header
This lesson isn’t saved. A free account remembers every lesson you finish.