Part 08 / Topic 8 of 10
CSV
CSV (comma-separated values) is a simple table format: each line is a row, and commas split the columns, like a spreadsheet saved as plain text. Excel and Google Sheets can open and save it.
Always open CSV files with newline="". Without it you can get blank rows between lines on Windows.
Real-world example: a student marks sheet.
import csv
with open("demo_marks.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["name", "maths", "science"])
writer.writerow(["Aarav", 88, 92])
writer.writerow(["Priya", 95, 89])
with open("demo_marks.csv", newline="", encoding="utf-8") as f:
for row in csv.reader(f):
print(row)
# ['name', 'maths', 'science']
# ['Aarav', '88', '92']
# ['Priya', '95', '89']
with open("demo_marks.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
total = int(row["maths"]) + int(row["science"]) # values are strings!
print(row["name"], total)
# Aarav 180
# Priya 184
Writing dicts with DictWriter:
import csv
results = [{"name": "Aarav", "grade": "A"}, {"name": "Priya", "grade": "A+"}]
with open("demo_results.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "grade"])
writer.writeheader()
writer.writerows(results)
with open("demo_results.csv", newline="", encoding="utf-8") as f:
print(f.read(), end="")
# name,grade
# Aarav,A
# Priya,A+
| Tool | Each row is | Good for |
|---|---|---|
csv.reader / csv.writer |
a list |
Simple tables, no header |
csv.DictReader / csv.DictWriter |
a dict (keys from header) |
โ Most real files, clear column names |
Do not split lines with
line.split(","). A value like"Pune, MH"has a comma inside. Thecsvmodule handles quotes for you.
๐ Going deeper: why
newline=""? Thecsvmodule writes its own line endings (\r\n) and must see quoted values that contain line breaks exactly as they are. Withoutnewline="", Windows turns\r\ninto\r\r\n, which shows up as blank rows. Files from Europe often use;: passdelimiter=";".
See examples/04_marks_csv_report.py.
Read more: the official csv documentation.
Done here? The practice set for Part 8 โ 8 exercises with solutions โ is on the part page.