Introduction
The csv module provides functionality for reading and writing CSV files.
Reading CSV
import csv
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# With headers
with open("data.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["age"])
Writing CSV
with open("output.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "City"])
writer.writerows([
["Alice", 30, "NYC"],
["Bob", 25, "LA"]
])
# With dictionaries
with open("output.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerow({"name": "Alice", "age": 30})
Custom Delimiters
# Tab-separated
writer = csv.writer(f, delimiter="\t")
# Custom quoting
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
Practice Problems
- Read CSV with different delimiters
- Convert CSV to dictionary
- Handle missing values in CSV
- Write nested data to CSV
- Merge multiple CSV files