Chapters
Python114 chapters

Exercises

CSV Files

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Write the rows as a CSV, then print the file.

Python
import csv

rows = [["name", "born"], ["Ada", 1815]]
# write people.csv, then print it
Exercise 2

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
Exercise 3

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(","))