Working with CSV Files
CSV (comma-separated values) is the format spreadsheets and many tools speak. The standard-library csv module handles the tricky details like quoting for you, so you almost never split on commas by hand.
To write rows, wrap the file in a csv.writer and call writerow():
import csv
rows = [["name", "score"], ["Ada", 90], ["Sam", 75]]
with open("scores.csv", "w", newline="") as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)The newline="" argument prevents blank lines between rows on some systems. Always include it when writing CSV.
To read rows back as dictionaries keyed by the header, use csv.DictReader. It reads the first line as the header automatically:
with open("scores.csv", "r", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["score"])Each row is a dict like {"name": "Ada", "score": "90"}. Note the values come back as strings, so convert with int(row["score"]) when you need a number.
Write a CSV called people.csv with header row name,age followed by Ada,36 and Sam,29. Then read it back with csv.DictReader and build a list of dicts named people. Finally compute the total age as an integer into a variable named total_age.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.