使用单个 with 语句根据条件打开多个文件

Open multiple files based on conditionals using a single with statement

我想使用 with 语句打开多个文件(因此我得到了上下文管理器的好处)基于布尔标志,这些标志指示我的程序是否应该实际打开每个文件。

我知道我可以使用 with 语句打开多个文件,例如:

with open('log.txt', 'w') as logfile, open('out_a.txt', 'w') as out_a, open('out_b.txt', 'w') as out_b:
    # do something with logfile, out_a and out_b
# all files are closed here

我想 运行 类似的语句,但是 只根据相应的标志 打开某些文件。我考虑过将其实现为 conditional_open 函数,例如:

write_log = True
write_out_a = False
write_out_b = True

with conditional_open('log.txt', 'w', cond=write_log) as logfile, open('out_a.txt', 'w', cond=write_out_a) as out_a, open('out_b.txt', 'w', cond=write_out_b) as out_b:
    # do something with logfile, out_a and out_b
# all files are closed here

但我对如何正确创建该函数感到有点困惑。理想情况下,coditional_open 将 return 一个打开的文件句柄或 None(在这种情况下文件永远不会 created/touched/deleted):

def conditional_open(filename, mode, cond):
    return open(filename, mode) if cond else None

但我担心这会在打开文件时跳过上下文管理器的好处,因为我正在从文件外部调用 open。这个假设正确吗?

任何人都可以提供一些关于我如何做到这一点的想法吗?我知道我可以根据条件创建模拟文件对象并改为写入它们,但这对我来说听起来有点太复杂了——这似乎是一个简单的问题,应该 有一个简单的Python.

中的解决方案

只需将您的功能设置为上下文管理器。

from contextlib import contextmanager

@contextmanager
def conditional_open(f_name, mode, cond):
    if not cond:
        yield None
    resource = open(f_name, mode)
    try:
        yield resource
    finally:
        resource.close()