我怎样才能避免:"ZipFile实例在提取zip文件时没有属性'__exit__''"?

geo*_*rge 4 python zipfile execfile

代码是:

import sys
execfile('test.py')
Run Code Online (Sandbox Code Playgroud)

在test.py我有:

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

此代码生成:

AttributeError ( ZipFile instance has no attribute '__exit__' ) # edited
Run Code Online (Sandbox Code Playgroud)

从python idle运行时,"test.py"中的代码有效.我正在运行python v2.7.10

小智 6

嗨也许迟到但我只是为我解决这个错误:).

我在python 2.7上创建我的代码但是当我把它放在使用2.6的服务器上时我有这个错误:

AttributeError: ZipFile instance has no attribute '__exit__'

为了解决这个问题,我在这篇文章中使用Sebastian的答案: 使用Python 2.6运行Python 2.7代码

import contextlib

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

像他说的那样:

contextlib.closing确实完成了ZipFile上缺少的exit方法应该做的事情.即,调用close方法

亲切的问候,(对不起我的英文)


mha*_*wke 0

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

import sys
print sys.version
Run Code Online (Sandbox Code Playgroud)

并且可以通过以下方式获取正在运行的解释器的位置

print sys.executable
Run Code Online (Sandbox Code Playgroud)

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