We found a Time Capsule buried in the code.
The old way of opening it (open() then close()) is risky. If we forget to lock it back up (close()), the time magic leaks out!
We need a spell that automatically seals the capsule when we're done.
The "With" Spell
Python has a special keyword called with. It acts like a temporary magic shield.
- It opens the file.
- It lets you do your work.
- It automatically closes the file for you, no matter what happens!
# The "With" Context Manager
with open("capsule.txt", "r") as file:
content = file.read()
print(content)
# Look ma, no close()!
# The file is already closed here.
1
The Old Code
Look at main.py. It uses the old, unsafe way.
2
Refactor
Rewrite the code using the with statement.
3
Indent
Remember: The code inside the with block must be indented (moved to the right).
This is called a Context Manager. It manages the "context" (opening and closing) for you. It's how professional Python Architects work.
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
with open("capsule.txt", "r") as file:
content = file.read()
print("Capsule says: " + content)Advanced TipsWant more? Click to expandClick to collapse
F. Why "with"?
- Safety: Even if your code crashes inside the block, Python guarantees the file will be closed.
- Cleanliness: Less code to write, less to forget.
- The "Context": It's like renting a car.
withhandles the rental agreement and the return; you just drive.
Loading...
Terminal
Terminal
Ready to run...