Ala*_*lan 3 python gzip python-2.6
我需要用 Python 处理 .gz 文件。
我将文件名传递到我的 Python 脚本中:
infile = sys.argv[1]
with gzip.open(infile, 'rb') as f:
logfile = f.read()
Run Code Online (Sandbox Code Playgroud)
这给了我:
with gzip.open(infile, 'rb') as f:
AttributeError: GzipFile instance has no attribute '__exit__'
Run Code Online (Sandbox Code Playgroud)
如果我手动压缩我的 .gz 文件,然后将其传递给我的 Python 脚本,一切正常。
logfile = open(infile, 'r').read()
Run Code Online (Sandbox Code Playgroud)
注意:我使用的是 Python 2.6.6(r266:84292,2016 年 8 月 18 日,15:13:37)。我无法在这台计算机上更新 Python。如何使用 Python 2.6 处理 gzip 压缩的文本文件?
该模块的上下文管理器支持gzip是问题 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()
Run Code Online (Sandbox Code Playgroud)