Python Learning Series · @onlysamarrr · Day 27 / 30
Day 27 teaches the with statement and CSV files. with is a context manager: __enter__ sets things up and __exit__ cleans up, even on error. For CSV, use the csv module with newline="".
Phase: Intermediate · Reels: 131/450 – 135/450
Day 27 teaches the with statement and CSV files. with is a context manager: __enter__ sets things up and __exit__ cleans up, even on error. For CSV, use the csv module with newline="".
import csv, io
buf = io.StringIO()
rows = [["item", "amt"], ["tea", 20], ["coffee", 15]]
with io.StringIO() as out:
pass
writer = csv.writer(buf)
writer.writerows(rows)
buf.seek(0)
with io.StringIO(buf.getvalue(), newline="") as f:
total = sum(int(r["amt"]) for r in csv.DictReader(f))
print(total)
print(buf.getvalue())
35 item,amt tea,20 coffee,15
Spreadsheets, reports and exported data are CSV files in almost every business.
Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.
Q1. What is the total of amounts 20 and 15 in the example?
Q2. Why open CSV files with newline=""?
Q3. What does csv.DictReader give per row?
| 131/450 | Concept | with open kyun |
| 132/450 | Live demo | CSV read/write demo |
| 133/450 | Common mistake | File close bhoolna |
| 134/450 | Quiz | Quiz: CSV se total |
| 135/450 | Interview / real life | Interview: context manager |