Skip to content

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 coffee

Was this page helpful?

Let us know how we did