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

Ibo*_*lit 2 python contextmanager

说,我想打开一些文件并逐行处理.为了论证,让我们假设我想将每个文件中的第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
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 7

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

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)
Run Code Online (Sandbox Code Playgroud)