Working with CSV Files in Python
CSV (comma-separated values) is one of the most common plain-text formats for tabular data, readable by spreadsheets, databases, and countless other tools. Python's built-in csv module handles the fiddly details — like commas that appear inside a quoted value — that make CSV harder to parse correctly than it first looks with plain string splitting.
import csv
Brings in the module, part of the standard library.
csv.reader(file)
Wraps an open file, yielding each row as a list of string values.
csv.writer(file)
Wraps an open file for writing; .writerow() writes one row at a time from a list of values.
DictReader and DictWriter
Work the same way, but read and write rows as dictionaries keyed by column name, using the first row as headers.
Use newline="" when opening on Windows
Avoids the csv module inserting unwanted extra blank lines.
import csv with open("people.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerow(["name", "age"]) writer.writerow(["Ada", 28]) writer.writerow(["Grace", 34]) with open("people.csv", "r", newline="") as f: reader = csv.reader(f) for row in reader: print(row)Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.