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
statement:
try:
with open('a', 'w') as a and open('b', 'w') as b:
do_something()
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?
Since Python 3.3, you can use the class
ExitStack
from thecontextlib
module to safelyopen an arbitrary number of files.
It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.
In fact, the canonical use-case that is mentioned in the documentation is managing a dynamic number of files.
If you are interested in the details, here is a generic example in order to explain how
ExitStack
operates:Output:
Just replace
and
with,
and you're done:Nested with statements will do the same job, and in my opinion, are more straightforward to deal with.
Let's say you have inFile.txt, and want to write it into two outFile's simultaneously.
EDIT:
I don't understand the reason of the downvote. I tested my code before publishing my answer, and it works as desired: It writes to all of outFile's, just as the question asks. No duplicate writing or failing to write. So I am really curious to know why my answer is considered to be wrong, suboptimal or anything like that.
As of Python 2.7 (or 3.1 respectively) you can write
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.With python 2.6 It will not work, we have to use below way to open multiple files:
For opening many files at once or for long file paths, it may be useful to break things up over multiple lines. From the Python Style Guide as suggested by @Sven Marnach in comments to another answer: