Concept Flow - Automatic resource cleanup
Start
Open resource
Use resource
Exit block or error
Automatic cleanup
End
This flow shows how a resource is opened, used, and then automatically cleaned up when leaving the block or if an error happens.
with open('file.txt', 'w') as f: f.write('Hello') # file is automatically closed here
| Step | Action | Resource State | Output |
|---|---|---|---|
| 1 | Enter with block, open file | file.txt opened for writing | |
| 2 | Write 'Hello' to file | file.txt open and writing | |
| 3 | Exit with block | file.txt closed automatically | |
| 4 | After block | file.txt closed |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| f | undefined | file object opened | file object open | file object closed | file object closed |
Automatic resource cleanup uses the with statement. Syntax: with resource as var: use resource When the block ends, Python calls cleanup automatically. This prevents resource leaks and errors. Works even if errors happen inside the block.