PythonMastery
Python programs · Files · beginner

Read a CSV file in Python

Read a CSV file with the csv module: each row becomes a dictionary keyed by the header. Also shows converting numbers and totalling a column.

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

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.

Learn the idea: CSV, JSON, and JSONL: Structured Text Done Right, File I/O, Pathlib, and Large Files

A longer explanation: How do I read a CSV file in Python?