Concept Flow - Handling multiple resources
Open resource 1
Use resource 1
Close resource 2
Close resource 1
END
Open multiple resources, use them, then close them in reverse order automatically.
with open('file1.txt') as f1, open('file2.txt') as f2: data1 = f1.read() data2 = f2.read()
| Step | Action | Resource State | Variables | Output |
|---|---|---|---|---|
| 1 | Open file1.txt as f1 | file1.txt open | f1=open file1.txt | |
| 2 | Open file2.txt as f2 | file1.txt open, file2.txt open | f1=open file1.txt, f2=open file2.txt | |
| 3 | Read from f1 | both files open | data1=contents of file1.txt, f1,f2 open | |
| 4 | Read from f2 | both files open | data1=..., data2=contents of file2.txt | |
| 5 | Exit with block, close f2 | file1.txt open, file2.txt closed | data1, data2 | |
| 6 | Close f1 | file1.txt closed, file2.txt closed | data1, data2 |
| Variable | Start | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|
| f1 | None | open file1.txt | open file1.txt | closed |
| f2 | None | open file2.txt | open file2.txt | closed |
| data1 | None | contents of file1.txt | contents of file1.txt | contents of file1.txt |
| data2 | None | None | contents of file2.txt | contents of file2.txt |
Use 'with' to open multiple resources:
with open(file1) as f1, open(file2) as f2:
# use f1 and f2
Resources auto-close after block ends.
This prevents forgetting to close files and resource leaks.