Reputation: 9622
This question is related to this question: How can I open multiple files using "with open" in Python?
I could have three sets of files: files1, files2 and file3
I can open files1 and files2 for reading and file3 for writing by doing this:
with fileinput.input(files=files1) as f1, fileinput.input(files=files2) as f2, open(file3,'w') as f3:
In Python 3 (not Python 2), how could I achieve this, if I had hundreds of sets of files?
I had a look at the contextlib module, but I'm not sure, how I would do this in the most Pythonic way.
http://docs.python.org/3/library/contextlib.html#contextlib.ExitStack
Upvotes: 0
Views: 303
Reputation: 104722
I think the contextlib.ExitStack
class you linked to is exactly what you want:
with contextlib.ExitStack() as stack:
inputs = [stack.enter_context(fileinput.input(files=filename))
for filename in input_filenames]
outputs = [stack.enter_context(open(filename, "w"))
for filename in output_filenames]
# do stuff with inputs and outputs here
This structure will guarantee that all open files will be closed if there is an exception raised at any point, including during the opening of the later files.
Upvotes: 3