Reading a CSV
import csv
with open("scores.csv") as f:
reader = csv.reader(f)
for row in reader:
print(row)
With Headers โ DictReader
with open("scores.csv") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["score"])
Writing a CSV
rows = [
["name", "score"],
["Ming", 85],
["Amy", 92],
]
with open("out.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
Handling Special Characters
If your data contains commas or quotes, csv.writer automatically quotes them โ do not try to hand-roll CSV output.
Reading Large Files
CSV readers stream row-by-row, so they work on very large files without loading everything into memory.
Practise this on PyForm โ free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm โ