gpt4 book ai didi

python - GzipFile 实例在 '__exit__' block 中使用时没有属性 "with:"

转载 作者:行者123 更新时间:2023-11-28 22:20:44 25 4
gpt4 key购买 nike

我需要用 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()

注意:我使用的是 Python 2.6.6(r266:84292,2016 年 8 月 18 日,15:13:37)。我无法在此计算机上更新 Python。如何使用 Python 2.6 处理 gzip 文本文件?

最佳答案

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

关于python - GzipFile 实例在 '__exit__' block 中使用时没有属性 "with:",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48736692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com