csv.DictReader() vs csv.DictWriter()
csv.DictReader() and csv.DictWriter() are both Python CSV Module APIs, and choosing between them is a common point of confusion. This page compares their syntax, parameters, return values, and typical use cases so you can pick the right one. csv.DictReader(): Returns a reader that maps each row to a dict with field names as keys. Its syntax is csv.DictReader(csvfile, fieldnames=None, **fmtparams), and it returns dictReader iterator csv.DictWriter(): Returns a writer that maps dicts to CSV rows using fieldnames. Its syntax is csv.DictWriter(csvfile, fieldnames, **fmtparams), and it returns dictWriter object Example of csv.DictReader(): with open("data.csv") as f:
for row in csv.DictReader(f):
print(row["Name"]) # Access by column name. Example of csv.DictWriter(): with open("out.csv", "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=["N","A"])
w.writeheader()
w.writerow({"N":"Alice", "A":30}). Read the full references for csv.DictReader() and csv.DictWriter() to see parameters, edge cases, and example code side by side. Other CSV Module APIs worth comparing: csv.reader(), csv.writer(), csv.writer.writerow(), csv.writer.writerows(), csv.Sniffer().sniff().