【问题标题】:How can I avoid: "ZipFile instance has no attribute '__exit__''" when extracting a zip file?提取 zip 文件时如何避免:“ZipFile 实例没有属性 '__exit__''”?
【发布时间】:2015-12-29 07:30:21
【问题描述】:

代码是:

import sys
execfile('test.py')

在 test.py 我有:

import zipfile
with zipfile.ZipFile('test.jar', 'r') as z:
    z.extractall("C:\testfolder")

这段代码产生:

AttributeError ( ZipFile instance has no attribute '__exit__' ) # edited

“test.py”中的代码在 python idle 运行时有效。 我正在运行 python v2.7.10

【问题讨论】:

  • 标题写着__exit__,问题里的错误写着extractall,哪一个是相关的?
  • 如果你尝试直接执行test.py,是否也会发生同样的情况?此外,您应该添加第二个反斜杠或使用 r"C:\testfolder" 以避免 \t 成为制表符。

标签: python zipfile execfile


【解决方案1】:

我在 python 2.7 上编写了我的代码,但是当我把它放在使用 2.6 的服务器上时,我遇到了这个错误:

AttributeError: ZipFile instance has no attribute '__exit__'

为了解决这个问题,我在这篇文章中使用了塞巴斯蒂安的回答: Making Python 2.7 code run with Python 2.6

import contextlib

def unzip(source, target):
    with contextlib.closing(zipfile.ZipFile(source , "r")) as z:
        z.extractall(target)
    print "Extracted : " + source +  " to: " + target

就像他说的:

contextlib.closing 完全符合缺少的 exit 方法 ZipFile 应该这样做。即调用close方法

【讨论】:

    【解决方案2】:

    根据 Python 文档,ZipFile.extractall() 是在 2.6 版中添加的。我希望您会发现您运行的 Python 版本与 idle 正在使用的版本不同,较旧(2.6 之前)。你可以用这个找出哪个版本:

    import sys
    print sys.version
    

    运行解释器的位置可以通过

    获得
    print sys.executable
    

    您的问题的标题支持执行旧版本 Python 的可能性,因为 with 语句/上下文管理器(具有 __exit__() 方法的类)直到 2.6 才引入(如果明确启用,则为 2.5) .

    【讨论】:

    • 刚刚在 Python 3.4.1 下尝试过,没有出现奇怪的错误。显然,使用不同的 .zip 文件。如果不是 Python 版本问题,可能是损坏的 zip 文件问题? (从命令行检查zip -T file
    • 抱歉,出现复制粘贴错误。错误读取“” ...没有属性退出
    • 导入系统打印系统版本;返回:2.7.10(默认,2015 年 5 月 23 日,09:44:00)[MSC v.1500 64 位 (AMD64)]
    • @马丁·埃文斯;不。从空闲运行时我没有遇到任何问题,因此档案被提取@nigel222。我尝试使用不同的 zip 文件,都返回相同的问题
    • [interpreter:] python 2.7.10 附带的标准空闲。 [sys.executable] 在空闲输出中:C:\Python27\pythonw.exe;外部空闲返回:无
    猜你喜欢
    • 2020-08-07
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2022-01-04
    相关资源
    最近更新 更多