python: `with open()` 和未知数量的文件

python: `with open()` and unknown number of files

比如说,我想打开一些文件并逐行处理它们。为了争论,假设我想将每个文件中的第 n 行连接成一行并将其写入另一个文件。我不想膨胀我的记忆,所以我不想完整地阅读它们。而且我不知道我的函数会得到多少文件。

如果我知道文件的数量,我会这样做:

with open(file_a) as in_a, open(file_b) as in_b, open(file_c, "w") as out:
    try:
        while True:
            line_a = next(in_a)
            line_b = next(in_b)
            out.write(line_a + line_b)
    except StopIteration:
        pass

有没有办法对未知数量的输入(或其他上下文管理器)做类似的事情?

使用contextlib.ExitStack() object跟踪任意数量的上下文管理器:

from contextlib import ExitStack

with ExitStack() as stack, open(file_c, "w") as out:
    infiles = [stack.enter_context(open(fname)) for fname in filenames]
    for lines in zip(*infiles):
        out.writelines(lines)