如何“打开”文件列表并在python中获取它们的句柄?

时间:2016-09-30 02:46:44

标签: python with-statement

是否可以with open()列表中包含的所有文件并创建用于写入的文件句柄?

例如,如果我的函数接受机器学习任务中数据分割的文件名列表,

fname_list = ['train_dataset.txt', 'validate_dataset.txt', 'test_dataset.txt']

然后能够做到这一点很方便:

with open('source_dataset.txt) as src_file, open(name_list, 'w') as <DONT_KNOW_WHAT_TO_DO_HERE>:

并在块内执行一些数据分割。

编辑:所以我的问题基本上是“是否可以为使用'with open()'打开的文件列表获取多个文件句柄?”

2 个答案:

答案 0 :(得分:2)

在Python 3.3及更高版本中,contextlib.ExitStack可用于正确而恰当地执行此操作:

from contextlib import ExitStack

with open('source_dataset.txt') as src_file, ExitStack() as stack:
    files = [stack.enter_context(open(fname, 'w')) for fname in fname_list]
    ... do stuff with src_file and the values in files ...
... src_file and all elements in stack cleaned up on block exit ...

答案 1 :(得分:1)

您可以定义类openfiles以支持with语句:

class openfiles:
    def __init__(self, filelist, mode='r'):
        self.fhandles = [open(f, mode) for f in filelist]

    def __enter__(self):
        return self.fhandles

    def __exit__(self, type, value, traceback):
        map(file.close, self.fhandles)

然后你可以:

with openfiles(['file1', 'file2']) as files:
    for f in files:
        print(f.read())