【问题标题】:One context manager instead of two for open file?一个上下文管理器而不是两个用于打开文件?
【发布时间】:2020-04-02 16:37:36
【问题描述】:

我的问题看起来类似于this one,但不确定...我想解析一些有时在 gzip 中压缩的日志文件,有时不是。

我有以下内容:

if file[-3:] == ".gz":
     with gzip.open(file, 'rb') as f:
          # do something
else:
    with open(file) as f:
          # do the same thing.

是否可以只有一个with 语句?

【问题讨论】:

  • 这可能是可能的,但我认为这会更令人困惑。也许只是将something 放在一个函数中,这样你就不会重复你的代码。
  • 你试过`with ... if ... else ...´吗?

标签: python python-3.x with-statement


【解决方案1】:
fn = gzip.open if file.endswith('.gz') else open

with fn(file, 'rb') as f:
    ...

另请注意,对返回上下文管理器的函数的调用不必发生在 with 行内:

if file.endswith('.gz'):
    ctx = gzip.open(file, 'rb')
else:
    ctx = open(file)

with ctx as f:
    ...

【讨论】:

    【解决方案2】:

    你可以把条件语句放在with这一行:

    with gzip.open(file, 'rb') if file[-3:] == '.gz' else open(file) as f:
       processFile(f)
    

    【讨论】:

      【解决方案3】:

      把你的“做某事”放在一个函数中

      def processFile(f)
              Do Something...
      
      if file[-3:] == ".gz":
           with gzip.open(file, 'rb') as f:
                processFile(f)
      else:
          with open(file) as f:
                processFile(f)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-28
        • 1970-01-01
        • 2013-10-25
        • 1970-01-01
        • 2014-05-13
        相关资源
        最近更新 更多