How do I read and write CSV files in Python?
· Category: Python Programming
Short answer
Python's built-in csv module provides csv.reader and csv.writer for basic CSV handling, and csv.DictReader / csv.DictWriter for working with dictionaries keyed by column headers.
Steps
- Open the file in text mode.
- Create a reader or writer object.
- Iterate over rows or write rows.
import csv
# Reading
with open("data.csv", "r", encoding="utf-8", newline="") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# Writing
with open("output.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(["name", "age"])
writer.writerows([["Alice", 30], ["Bob", 25]])
Tips
- Always open CSV files with
newline=""to prevent extra blank lines on Windows. - Use
DictReaderto access columns by name instead of index. - Specify
delimiter,quotechar, andquotingfor non-standard formats.
# DictReader
with open("data.csv", "r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["age"])
Common issues
- Missing
newline=""causes double line endings on Windows. - Mixing text and binary modes causes
csvmodule errors. - Very large CSV files may require streaming line-by-line instead of loading everything into memory.