Processing CSV Data with the csv Module
Reading CSV
Section titled “Reading CSV”import csv
with open("input.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row)Writing CSV
Section titled “Writing CSV”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
Section titled “Common cleanup”- strip whitespace
- handle missing values
- normalize casing
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading