Python CSV Files
In this page:
The csv Module
CSV (Comma-Separated Values) is a plain-text format for tabular data, and Python's built-in csv module handles the tricky edge cases (commas inside quoted fields, escaped quotes) that make manually splitting on ',' unreliable for real-world CSV files.
Example: The csv Module
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["name", "age"])
writer.writerow(["Alex, Jr.", 30])
print("CSV module handles commas inside quoted fields")
Reading CSV Files
csv.reader wraps an open file and yields each row as a list of string values, automatically handling quoted fields correctly -- you typically loop over the reader object directly to process the file one row at a time.
Example: Reading CSV Files
import csv
with open("data.csv", "w", newline="") as f:
csv.writer(f).writerow(["Alex", "30"])
with open("data.csv", "r", newline="") as f:
for row in csv.reader(f):
print(row)
Writing CSV Files
csv.writer wraps an open file (opened in write mode) and its .writerow() method correctly quotes fields containing commas or special characters for you, so you don't have to manually escape anything yourself.
Example: Writing CSV Files
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["name", "age"])
writer.writerow(["Alex", 30])
with open("data.csv") as f:
print(f.read())
DictReader and DictWriter
csv.DictReader turns each row into a dictionary keyed by the column headers instead of a plain list, so you can write row[email] instead of row[3] -- DictWriter does the reverse, letting you write rows from dictionaries.
Example: DictReader and DictWriter
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "email"])
writer.writeheader()
writer.writerow({"name": "Alex", "email": "[email protected]"})
with open("data.csv", newline="") as f:
for row in csv.DictReader(f):
print(row["email"])
Handling Delimiters
Not every CSV-like file actually uses commas -- some use tabs or semicolons -- and both csv.reader and csv.writer accept a delimiter parameter to handle those variants without you having to write custom parsing logic.
Example: Handling Delimiters
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f, delimiter=";")
writer.writerow(["name", "age"])
with open("data.csv", newline="") as f:
for row in csv.reader(f, delimiter=";"):
print(row)
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: