CSV (comma-separated values) is the universal tabular format — every spreadsheet and database can export it. Python's csv module reads and writes it correctly, handling the tricky cases (quoted fields, commas inside values) you'd get wrong by splitting on commas yourself.
Reading with DictReader
DictReader turns each row into a dict keyed by the header row — far clearer than positional indexing:
import csvwith open("students.csv", newline="") as f:reader = csv.DictReader(f) # uses the header row for keysfor row in reader:print(row["name"], row["package"]) # access by column name
Writing with DictWriter
with open("out.csv", "w", newline="") as f:writer = csv.DictWriter(f, fieldnames=["name", "package"])writer.writeheader()writer.writerow({"name": "Ana", "package": 7.5})writer.writerows([{"name": "Ravi", "package": 9.0},{"name": "Kai", "package": 6.5},])
Key takeaways
- 01The csv module handles quoting and delimiters correctly — don't split on commas yourself.
- 02DictReader maps each row to a dict keyed by the header; DictWriter writes them back.
- 03Always pass newline="" when opening CSV files.
- 04writeheader() then writerow(s) for output.
- 05For heavy analysis, pandas.read_csv is more powerful.
