Goal
You’ll be able to read from and write to files correctly, and understand why the with statement is genuinely the recommended way to handle files, not just a stylistic preference.
Learn
Python can read and write files using the built-in open() function:
file = open("notes.txt", "w")
file.write("Hello, file!")
file.close() # essential — releases the file The second argument to open() specifies the mode: "w" (write, overwrites existing content), "a" (append, adds to the end), "r" (read, the default).
Here’s the genuinely important practice: using with automatically handles closing the file for you, even if an error occurs partway through — this matters because forgetting .close(), or an error happening before it’s reached, can leave a file improperly closed, potentially causing data loss or file-locking issues:
with open("notes.txt", "w") as file:
file.write("Hello, file!")
# file is automatically closed here, even if an error occurred above Reading a file’s contents:
with open("notes.txt", "r") as file:
content = file.read()
print(content)
with open("notes.txt", "r") as file:
for line in file:
print(line.strip()) # reads line by line The with pattern is called a context manager — it guarantees proper cleanup (closing the file) regardless of whether the code inside runs successfully or raises an exception partway through, which manually calling .close() yourself doesn’t guarantee if an error happens before that line is reached.
Decision Task
You write file = open(“data.txt”, “w”) followed by several lines of processing, then file.close() at the very end — but one of the processing lines raises an exception partway through. Before reading on: does file.close() still run in this case, and what problem could this cause?
Show Answer
No, file.close() does NOT run — if an exception is raised before that line is reached, the program jumps to exception handling (or crashes), skipping the close() call entirely. This can leave the file improperly closed, potentially causing data loss (unwritten buffered content) or file-locking issues, which is exactly the specific real-world problem the with statement is designed to prevent automatically.
Common Mistake
Manually calling open() and .close() separately instead of using a with block, especially in any code where an error could plausibly occur between opening and closing the file. If an exception happens in between, manual .close() gets skipped entirely, but with automatically ensures proper cleanup regardless of whether an error occurred, which is exactly why it’s the strongly recommended pattern for real code.
Practice Questions
1. Write code using with that opens “log.txt” in append mode and writes the line “Event logged.”.
Show Answer
with open("log.txt", "a") as file:\n file.write("Event logged.")
2. What does the “w” mode do if the file already has content?
Show Answer
Overwrites/erases the existing content entirely, starting fresh.
3. What does the “a” mode do differently from “w”?
Show Answer
Appends new content to the end of the existing file, rather than overwriting it.
4. True or False: using with guarantees a file gets properly closed even if an error occurs inside the block.
Show Answer
True — this is exactly the real, practical benefit of the with/context manager pattern over manual open()/close().
5. Write code that reads all lines from “data.txt” one at a time, printing each with trailing whitespace stripped.
Show Answer
with open("data.txt", "r") as file:\n for line in file:\n print(line.strip())
Try It Yourself
Without looking back, write code using with that reads the entire contents of “report.txt” into a single variable and prints it.
Show Answer
with open("report.txt", "r") as file:\n content = file.read()\n print(content) — using with ensures the file is properly closed automatically once the block finishes.
Quick Check
1. What does the “w” file mode do to existing content?
Show Answer
Overwrites/erases it entirely.
2. What does the “a” file mode do?
Show Answer
Appends new content to the end of the file, without erasing what’s already there.
3. Why is the with statement genuinely recommended over manual open()/close()?
Show Answer
It guarantees the file is properly closed even if an error occurs inside the block, unlike manual close() which gets skipped if an exception happens first.
4. What is the with pattern technically called?
Show Answer
A context manager.
5. What method reads a file’s entire contents into one string at once?
Show Answer
.read()