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?

Intermediate

Answer

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 correctly
Real-world example Reading from one file and writing to another simultaneously, with both files guaranteed to be properly closed.

Common follow-ups: In what order are the context managers' __exit__ methods called if an exception occurs partway through the block?