Python Learning Series · @onlysamarrr · Day 27 / 30

Day 27: with Statement and CSV

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

Quick Answer

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="".

What You Will Learn

Code

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())

Output

35
item,amt
tea,20
coffee,15

Code Explained, Line by Line

  1. csv.writer writes rows in CSV format.
  2. newline="" is required when opening CSV files, or extra blank lines appear.
  3. csv.DictReader turns each row into a dict, so values are read by column name (r["amt"]).
  4. sum(...) totals all amounts: in the example the total is 35.
  5. with closes the file or buffer itself, so forgetting close() is no longer a risk.
Common Mistake: Forgetting close() after open() can leave data unsaved or the file locked. Always use with.

Real-Life Use

Spreadsheets, reports and exported data are CSV files in almost every business.

Practice Task: Build a CSV of items and amounts, then use DictReader to find the total.

Test Yourself — MCQs

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?

Today's 5 Reels (from the 90-Day Plan Excel)

131/450Conceptwith open kyun
132/450Live demoCSV read/write demo
133/450Common mistakeFile close bhoolna
134/450QuizQuiz: CSV se total
135/450Interview / real lifeInterview: context manager
← Day 26Day 28 →