Exercises
CSV Files
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Write the rows as a CSV, then print the file.
Python
import csv
rows = [["name", "born"], ["Ada", 1815]]
# write people.csv, then print it
Open with newline="" and use csv.writer.
import csv
rows = [["name", "born"], ["Ada", 1815]]
with open("people.csv", "w", encoding="utf-8", newline="") as f:
csv.writer(f).writerows(rows)
with open("people.csv", encoding="utf-8") as f:
print(f.read().strip())Exercise 2Passed
Read the file by column name and print each name with its year plus 100.
Python
import csv
with open("people.csv", "w", encoding="utf-8", newline="") as f:
csv.writer(f).writerows([["name", "born"], ["Ada", 1815], ["Grace", 1906]])
# read it back by column name
DictReader uses the header row.
import csv
with open("people.csv", "w", encoding="utf-8", newline="") as f:
csv.writer(f).writerows([["name", "born"], ["Ada", 1815], ["Grace", 1906]])
with open("people.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
print(row["name"], int(row["born"]) + 100)Exercise 3Passed
This field contains a comma. Parse it properly so there are three fields.
Python
import csv
import io
line = 'Ada,"maths, and computing",1815'
print(line.split(","))csv.reader accepts any iterable of lines, including a StringIO.
import csv
import io
line = 'Ada,"maths, and computing",1815'
print(next(csv.reader(io.StringIO(line))))