Frantischeck003 Frantischeck003 - 1 year ago 116
Python Question

How can I open multiple files using "with open" in Python?

I want to change a couple of files at one time, iff I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the


with open('a', 'w') as a and open('b', 'w') as b:
except IOError as e:
print 'Operation failed: %s' % e.strerror

If that's not possible, what would an elegant solution to this problem look like?

Answer Source

As of Python 2.7 (or 3.1 respectively) you can write

with open('a', 'w') as a, open('b', 'w') as b:

In earlier versions of Python, you can sometimes use contextlib.nested() to nest context managers. This won't work as expected for opening multiples files, though -- see the linked documentation for details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download