【问题标题】:Open multiple files based on conditionals using a single with statement使用单个 with 语句根据条件打开多个文件
【发布时间】:2020-03-16 10:01:00
【问题描述】:

我想使用基于布尔标志的 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_openfunction,类似于:

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 将返回打开的文件句柄或None(在这种情况下,文件永远不会被创建/触摸/删除):

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

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

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

【问题讨论】:

    标签: python file io conditional-statements with-statement


    【解决方案1】:

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

    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()
    

    【讨论】:

      猜你喜欢
      • 2014-01-15
      • 2014-03-07
      • 2016-06-03
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多