Skip to content
Python

CSV Processing

Read and write CSV files using the csv module.

By EZ4Code Team
csvfile

Code

import csv

# Write CSV
with open("data.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "age", "city"])
    writer.writeheader()
    writer.writerow({"name": "Alice", "age": 30, "city": "Beijing"})

# Read CSV
with open("data.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])

Explanation

csv.DictReader/DictWriter handle CSV as dictionaries, making field access more intuitive.

More Python Snippets