GzipFile实例没有属性' __退出__'当用于" with:"块

时间:2018-02-11 21:32:14

标签: python gzip

我需要使用python处理.gz文件。

我将文件名传递给我的python脚本:

 infile=sys.argv[1]

 with gzip.open(infile, 'rb') as f:
     logfile = f.read()

给了我:

  with gzip.open(infile, 'rb') as f:
  AttributeError: GzipFile instance has no attribute '__exit__'

如果我手动gunzip我的gz文件然后将其传递给我的python脚本一切正常。

  logfile = open(infile, 'r').read()

2 个答案:

答案 0 :(得分:2)

gzip模块的上下文管理器支持为issue 3860

它在Python 3.1 alpha 1(在3.x行中)和2.7 alpha 1(在2.x行中)中修复。它仍然在2.6.6中打开,你在这里使用它。

当然,您可以通过不使用上下文管理器语法来解决这个问题:

import sys, gzip

logfile = gzip.open(sys.argv[1], 'rb').read()

答案 1 :(得分:1)

This的答案突出显示了使用contextlib来调用close方法。

with contextlib.closing(gzip.open(inputFileName,'rb')) as openedFile:
    # processing code 
    # for line in openedFile:
    # ...