The csv module
In part 6 you read CSV files by splitting each line yourself. That works until a value contains the separator itself, which happens more often than you'd think. The standard library's csv module reads CSV files properly. Here is the pets file from part 6 again, read with it:
Rex;dog;4
Misty;cat;11
Bubbles;fish;1import csv
with open("pets.csv") as file:
for row in csv.reader(file, delimiter=";"):
print(row)
['Rex', 'dog', '4']
['Misty', 'cat', '11']
['Bubbles', 'fish', '1']csv.reader(file, delimiter=";") goes through the file one line at a time, and gives each line as a list of its values, already without the line break at the end, so there's nothing to strip. The delimiter is the character between the values. Leave it out and the reader assumes a comma: the C in CSV stands for comma, after all, although semicolons are common too.
The values are strings
As with split, every value is a string. Convert numbers yourself before calculating with them:
Rex;dog;4
Misty;cat;11
Bubbles;fish;1import csv
total = 0
with open("pets.csv") as file:
for row in csv.reader(file, delimiter=";"):
name = row[0]
age = int(row[2])
total += age
print(f"{name} is {age}")
print("Total age:", total)
Rex is 4
Misty is 11
Bubbles is 1
Total age: 16Why not split?
A value that contains the delimiter is put in double quotes. Spreadsheet programs do this when they save a CSV file. split doesn't know about quotes, but the csv module does:
"Python, the basics",Ada Lovelace,2026
Short stories,"King, Stephen",2019import csv
with open("books.csv") as file:
for line in file:
print(line.strip().split(","))
with open("books.csv") as file:
for row in csv.reader(file):
print(row)
['"Python', ' the basics"', 'Ada Lovelace', '2026']
['Short stories', '"King', ' Stephen"', '2019']
['Python, the basics', 'Ada Lovelace', '2026']
['Short stories', 'King, Stephen', '2019']Split cuts the titles and names in two and keeps the quotes. The reader gives three clean values per line.
csv.reader works on anything that gives lines of text, not only on an open file. A list of strings will do, which is handy for trying it out:
>>> import csv
>>> lines = ['Ada;"Lovelace; Countess";1815']
>>> for row in csv.reader(lines, delimiter=";"):
... print(row)
...
['Ada', 'Lovelace; Countess', '1815']