Python CSV Files
In this page:
import csv
with open("file.csv", newline="") as file:
for row in csv.reader(file):
# row is a list
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]) # comma inside the value is handled correctly
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): # each row comes back as a list of strings
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"]) # header row
writer.writerow(["Alex", 30]) # data row, values quoted/escaped automatically
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): # each row comes back as a dict keyed by header
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=";") # use ; instead of , as the separator
writer.writerow(["name", "age"])
with open("data.csv", newline="") as f:
for row in csv.reader(f, delimiter=";"):
print(row)
- Opening a CSV file without
newline="", which can produce blank lines between rows on Windows. - Splitting lines with
line.split(",")instead of thecsvmodule, which breaks on quoted fields containing commas. - Forgetting that every value read is a string, so
row[1] + 1fails until you convert withint().
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: