Python The csv Module
A CSV file stores a table as plain text. Each line is one row, and commas separate the values in a row.
Read rows as lists
csv.reader gives you one list per row.
import csv
with open("scores.csv", newline="") as file:
reader = csv.reader(file)
for row in reader:
print(row)Commas inside quotes
Quotes protect a comma inside a value. The reader keeps that value whole.
import csv
with open("notes.csv", newline="") as file:
reader = csv.reader(file)
for row in reader:
print(row)Write rows to a file
csv.writer turns each list into one line. It adds quotes only when a value needs them.
import csv
with open("pets.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["name", "pet"])
writer.writerow(["Ana", "cat"])Read rows as dictionaries
DictReader uses the header row as keys. You read values by name, not by position.
import csv
with open("scores.csv", newline="") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["name"], row["score"])Write dictionaries
DictWriter needs the field names first. writeheader() writes the header row.
import csv
with open("pets.csv", "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["name", "pet"])
writer.writeheader()
writer.writerow({"name": "Ana", "pet": "cat"})Example
import csv
with open("scores.csv", newline="") as file:
reader = csv.DictReader(file)
rows = list(reader)
for row in rows:
score = int(row["score"])
if score >= 90:
row["grade"] = "A"
elif score >= 80:
row["grade"] = "B"
else:
row["grade"] = "C"
with open("graded.csv", "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["name", "score", "grade"])
writer.writeheader()
writer.writerows(rows)
with open("graded.csv") as file:
print(file.read(), end="")Key points
- CSV: a plain text file that stores a table
- Use newline="" when you open a CSV file
- Use csv.reader to read each row as a list of strings
- Use csv.DictReader to read each row as a dictionary
- Use int() or float() to turn text values into numbers
In this example, scores.csv holds a name and a score for three students. DictReader reads each row as a dictionary. The loop turns each score into an int. Scores of 90 or more earn an A. Scores of 80 or more earn a B. Lower scores earn a C. DictWriter then writes the rows to graded.csv. It adds grade as a third column. The last lines read the new file as plain text and print it.
Note
Never split a CSV line by hand with split(",").
A quoted value can hold a comma.
Splitting would break that value in two.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Why should you not split a CSV line with line.split(",")?