snippetpythonCriticalCanonical
How can I open multiple files using "with open" in Python?
Viewed 0 times
withhowfilesusingmultipleopencanpython
Problem
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
If that's not possible, what would an elegant solution to this problem look like?
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.strerrorIf that's not possible, what would an elegant solution to this problem look like?
Solution
As of Python 2.7 (or 3.1 respectively) you can write
(Historical note: In earlier versions of Python, you can sometimes use
In the rare case that you want to open a variable number of files all at the same time, you can use
Note that more commonly you want to process files sequentially rather than opening all of them at the same time, in particular if you have a variable number of files:
with open('a', 'w') as a, open('b', 'w') as b:
do_something()(Historical note: 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.)In the rare case that you want to open a variable number of files all at the same time, you can use
contextlib.ExitStack, starting from Python version 3.3:with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Do something with "files"Note that more commonly you want to process files sequentially rather than opening all of them at the same time, in particular if you have a variable number of files:
for fname in filenames:
with open(fname) as f:
# Process fCode Snippets
with open('a', 'w') as a, open('b', 'w') as b:
do_something()with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Do something with "files"for fname in filenames:
with open(fname) as f:
# Process fContext
Stack Overflow Q#4617034, score: 1504
Revisions (0)
No revisions yet.