CSV files
🌍 In real life. A class marks sheet is a table: one row per student, columns for name and score, and a top row naming the columns. Save it from a spreadsheet as CSV, and you get a plain text file where each row is a line and commas separate the columns.
Python's csv module reads and writes those tables for you.
The idea in one sentence: a CSV file stores a table as lines of comma-separated values, and csv.reader turns each line into a list of strings (or csv.DictReader into a dictionary).
Its words:
- CSV: comma-separated values
- header: the first row, naming the columns
csv.reader(f): gives each row as a list;next(reader)takes one row, like the headercsv.DictReader(f): gives each row as a dictionary keyed by the headercsv.writer(f).writerow([...]): writes one row
Step by step, for name,score then Ana,9:
next(reader)reads the header:['name', 'score'].- The loop's first row is
['Ana', '9']: two strings. int(row[1])turns the score into the number 9.
The csv module splits each line into a list for you. next(reader) takes the header row off first. Every value comes out as text, so turn numbers into numbers with int():
import csv
with open("scores.csv") as f:
reader = csv.reader(f)
header = next(reader)
print(header)
for row in reader:
print(row[0], "scored", int(row[1]))csv.DictReader uses the header for you: each row becomes a dictionary from column names to values.
import csv
with open("scores.csv") as f:
for row in csv.DictReader(f):
print(row["name"], row["score"])To write a CSV file, use csv.writer and writerow. Open the file with newline="" so the rows don't get extra blank lines on some computers.
import csv
with open("pets.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["pet", "legs"])
writer.writerow(["cat", 4])
writer.writerow(["bird", 2])
with open("pets.csv") as f:
for row in csv.reader(f):
print(row)Why not just split(",")? For simple files it works, but real CSV has surprises: a value can itself contain a comma if it's wrapped in quotes, like "Dhaka, Bangladesh". The csv module knows those rules, so it splits correctly where split(",") would break the value in two.
Mistakes and edge cases.
- Treating numbers as numbers. Every value is text:
"9" + "7"is"97". Convert withint()orfloat(). - Forgetting the header. Without
next(reader), the header row goes through your loop, andint("score")raises a ValueError. - Extra blank lines when writing. Open with
newline="". - A short row. A line with a missing value gives a shorter list, so
row[1]can raise an IndexError.
Quiz
What does this print?
print("Ana,9".split(","))What does this print?
import csv with open("t.csv", "w") as f: f.write("a,b\n1,2\n") with open("t.csv") as f: rows = list(csv.reader(f)) print(len(rows), rows[1])Why write
int(row[1])instead of justrow[1]?- csv gives every value as text
- row[1] is always 0
- To skip the header
What does this print?
import csv with open("t.csv", "w") as f: f.write("name,age\nBo,11\n") with open("t.csv") as f: for row in csv.DictReader(f): print(row["age"])Which line has a mistake, if every score should be added up?
import csv total = 0 with open("t.csv", "w") as f: f.write("name,score\nAna,9\n") with open("t.csv") as f: for row in csv.reader(f): total += int(row[1])
Coding tasks
Write
average_score(filename)that returns the average of the score column (after the header row).Write
top_names(filename, at_least)that returns a list of the names whose score is at least at_least, in file order.