CSV Reading & Writing
Python's csv module handles the quirks of comma-separated value files — quoted fields, embedded commas, and different delimiters.
Reading CSV
import csv
with open("data.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader)
print(header)
for row in reader:
print(row) # list of stringsDictReader
with open("data.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["age"]) # access by column nameWriting CSV
with open("output.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["name", "age", "city"])
writer.writerows([
["Alice", 30, "New York"],
["Bob", 25, "London"],
])DictWriter
fields = ["name", "age", "city"]
with open("output.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fields)
writer.writeheader()
writer.writerow({"name": "Carol", "age": 28, "city": "Tokyo"})Custom Dialect
with open("pipe.csv", "r", newline="") as f:
reader = csv.reader(f, delimiter="|", quotechar="'")