This question already has an answer here:
Is it possible to with open()
all files contained in a list and create file handles for writing?
For example, if my function accepts a list of filenames for data-splitting in a machine learning task,
fname_list = ['train_dataset.txt', 'validate_dataset.txt', 'test_dataset.txt']
then it would be convenient to be able to do:
with open('source_dataset.txt) as src_file, open(name_list, 'w') as <DONT_KNOW_WHAT_TO_DO_HERE>:
And perform some data splitting within the block.
Edit: So my question is basically "Is it possible to obtain multiple file handles for a list of files opened with 'with open()'?"
In Python 3.3 and higher,
contextlib.ExitStack
can be used to do this correctly and nicely:You can define a class
openfiles
to support thewith
statement:Then you can: