Lesson 11.3: The with Statement
What you will learn:
- What context managers are and why they matter
- How the
withstatement automatically closes files - Why
withis better than manual open/close - How to work with multiple files using
with
1. The Problem with Manual Closing
In the previous lessons, we always had to remember to call file.close(). But what if an error occurs before we reach that line?
What Can Go Wrong
file = open("data.txt", "r") content = file.read() result = 10 / 0 # This causes an error! file.close() # This line NEVER runs!
If an error occurs between open() and close(), the file stays open. Open files consume system resources and can prevent other programs from accessing the file. The with statement solves this problem.
2. The with Statement
The with statement automatically closes the file when the block ends, even if an error occurs:
Reading with the with Statement
# The file is automatically closed when the block ends with open("greeting.txt", "r") as file: content = file.read() print(content) # File is now closed - no need to call file.close() print("File is closed:", file.closed) # True
Welcome to Python.
Have a great day!
File is closed: True
Writing with the with Statement
with open("output.txt", "w") as file: file.write("Line 1\n") file.write("Line 2\n") file.write("Line 3\n") # File is automatically saved and closed here
3. Why with Is Better
Compare the two approaches:
Without with (Old Way)
# You have to remember to close file = open("data.txt", "r") try: content = file.read() # process content... finally: file.close() # Ensure file closes even if error
With the with Statement (Better Way)
# Cleaner, safer, and automatic with open("data.txt", "r") as file: content = file.read() # process content... # File is automatically closed
The with statement is preferred because it is:
- Safer: The file closes even if an error occurs
- Cleaner: Less code to write
- Clearer: It is obvious where the file is being used
4. Common Patterns with the with Statement
Reading and Processing Lines
with open("scores.txt", "r") as file: for line in file: name, score = line.strip().split(": ") print(f"{name} scored {score}")
Building a List from a File
with open("names.txt", "r") as file: names = [line.strip() for line in file] # The list is available after the with block print(f"Found {len(names)} names") print(names)
Appending with with
with open("journal.txt", "a") as file: entry = input("Today's journal entry: ") file.write(entry + "\n") print("Entry saved!")
5. Working with Multiple Files
You can open multiple files in a single with statement or nest them:
Copying Content Between Files
# Open two files at once with open("source.txt", "r") as source: with open("backup.txt", "w") as backup: for line in source: backup.write(line) print("Backup complete!")
Filtering Lines to a New File
# Copy only lines that contain "error" with open("app.log", "r") as log_file: with open("errors.log", "w") as error_file: for line in log_file: if "error" in line.lower(): error_file.write(line)
Check Your Understanding
What is the main advantage of using with open() as file: instead of file = open()?
The with statement automatically closes the file when the block ends, even if an error occurs. With the manual approach, if an error happens before file.close(), the file stays open, potentially causing resource leaks or data loss.
Key Takeaways
- The
withstatement automatically closes files when the block ends - Files are closed even if an error occurs inside the
withblock withis the recommended way to work with files in Python- You can nest
withstatements to work with multiple files - Data read inside a
withblock (stored in variables) remains available after the block - After the
withblock, the file object exists but is closed