A CSV file is a table saved as plain text: one row per line, with commas between the values. The csv module in the standard library reads it correctly, including values that contain commas inside quotes.
The program
python
import csv # create a small CSV file to read with open("scores.csv", "w", encoding="utf-8", newline="") as f: f.write("name,city,score\n") f.write("Ada,London,95\n") f.write('Linus,"Helsinki, Finland",87\n') f.write("Grace,New York,91\n") with open("scores.csv", encoding="utf-8", newline="") as f: reader = csv.DictReader(f) for row in reader: print(row["name"], "|", row["city"], "|", row["score"])
output
Ada | London | 95 Linus | Helsinki, Finland | 87 Grace | New York | 91
How it works
csv.DictReaderreads the first line as the header. Each later row becomes a dictionary, so you get a value by its column name:row["score"]."Helsinki, Finland"is in quotes in the file, so the comma inside it is part of the value. Splitting each line withline.split(",")would break this row into four values. Thecsvmodule handles it correctly.newline=""is what thecsvdocumentation asks for when you open a CSV file. It lets the module handle line endings itself.
Numbers are strings
Every value from a CSV file is a string, even 95. Convert it before you do maths:
python
import csv with open("scores.csv", "w", encoding="utf-8", newline="") as f: f.write("name,score\nAda,95\nLinus,87\nGrace,91\n") with open("scores.csv", encoding="utf-8", newline="") as f: scores = [int(row["score"]) for row in csv.DictReader(f)] print("Scores:", scores) print("Average:", round(sum(scores) / len(scores), 1))
output
Scores: [95, 87, 91] Average: 91.0
Related programs: Write a CSV file.