Processing CSV Data with the csv Module
Reading CSV
csv_read.py
import csv
with open("input.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row)csv_read.py
import csv
with open("input.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row)Writing CSV
csv_write.py
import csv
rows = [
{"name": "Alice", "score": 95},
{"name": "Bob", "score": 88},
]
with open("out.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "score"])
writer.writeheader()
writer.writerows(rows)csv_write.py
import csv
rows = [
{"name": "Alice", "score": 95},
{"name": "Bob", "score": 88},
]
with open("out.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "score"])
writer.writeheader()
writer.writerows(rows)Common cleanup
- strip whitespace
- handle missing values
- normalize casing
π§ͺ Try It Yourself
Exercise 1 β List Files with os.listdir
Exercise 2 β Join Paths with os.path.join
Exercise 3 β Write and Read a File
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
