Phase 2: Programming Fundamentals II · ~35 minutes · Python · uv
Reading and Writing Files
A file you wrote to but haven't closed can look completely empty to anything else that checks it — even though your program "already wrote" the data.
Hiring signal: Always uses with for file handling and can explain exactly why an unflushed write looks empty
What you will learn
- Open, read, and write files correctly using with blocks
- Explain why with matters: automatic, guaranteed closing and flushing, even if an error happens
- Reproduce and explain the surprising 'file looks empty before close()' buffering behavior
- Read and write CSV files using the csv module
Introduction
Type: Learn Languages: Python Prerequisites: Lesson 03 (Strings and Text Processing) Time: ~35 minutes
Objective
Learning objectives
- Open, read, and write files correctly using
with blocks - Explain why
with matters: automatic, guaranteed closing and flushing, even if an error happens - Reproduce and explain the surprising "file looks empty before
close()" buffering behavior - Read and write CSV files using the
csv module
What you're building
A script (transform_products.py) that:
- Writes a real CSV file (at least 5 rows) with columns
name and price, using csv.writer - Reads it back with
csv.DictReader, applies a transformation to the price column (e.g., a 10% price increase), and writes the result to a new CSV file - Uses
with for every file operation — no manual .close() calls - Contains a comment explaining, in your own words, why checking a file's contents before its writer has closed it can show stale or missing data
A script opens a file with open(path, "w") (no with, no explicit .close()), writes to it, and the script then crashes on an unrelated line before reaching the end. What's the most accurate prediction about the file's contents?
This is the direct real-world consequence of this lesson's buffering example. Without with (which guarantees a flush on exit, even during an exception) or an explicit, successfully-reached .close() call, there's no guarantee that buffered writes have actually reached disk by the time a crash happens elsewhere in the script. The data might be there, might be partially there, or might be missing — genuinely unreliable, which is exactly the case for using with by default rather than as an optional nicety.
Unlock the full lesson
You've read the first 2 sections. The rest of this lesson covers The Problem, Check Yourself, Key Terms & Next — plus a hands-on lab, quiz, and project artifact.
Create a free account to unlock Phase 0 and Phase 1 of every course — no credit card.
Browse all courses · View pricing · DeVenture Academy