Python › File I/O & Context Managers
How do you use multiple context managers in a single 'with' statement, and how does this compare to nesting separate 'with' blocks?
IntermediateAnswer
Separate multiple context managers with commas in one 'with' statement (`with open(a) as f1, open(b) as f2:`) — functionally equivalent to nesting them, but more concise; all context managers are entered left-to-right and exited in REVERSE order, exactly like nested blocks would be.
with open("input.txt") as infile, open("output.txt", "w") as outfile:
for line in infile:
outfile.write(line.upper())
# both files properly closed, even nested exceptions are handled correctlyReal-world example Reading from one file and writing to another simultaneously, with both files guaranteed to be properly closed.