How can I avoid: “ZipFile instance has no attribute '__exit__''” when extracting a zip file?

梦想的初衷 提交于 2021-02-07 14:47:50

问题


The code is:

import sys
execfile('test.py')

In test.py I have:

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

This code produces:

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

The code from "test.py" works when run from python idle. I am running python v2.7.10


回答1:


I made my code on python 2.7 but when I put it on my server which use 2.6 I have this error :

AttributeError: ZipFile instance has no attribute '__exit__'

For solve this problems I use Sebastian's answer on this post : 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

Like he said :

contextlib.closing does exactly what the missing exit method on the ZipFile would be supposed to do. Namely, call the close method




回答2:


According to the Python documentation, ZipFile.extractall() was added in version 2.6. I expect that you'll find that you are running a different, older (pre 2.6), version of Python than that which idle is using. You can find out which version with this:

import sys
print sys.version

and the location of the running interpreter can be obtained with

print sys.executable

The title of your question supports the likelihood that an old version of Python is being executed because the with statement/context managers (classes with a __exit__() method) were not introduced until 2.6 (well 2.5 if explicitly enabled).



来源:https://stackoverflow.com/questions/32884277/how-can-i-avoid-zipfile-instance-has-no-attribute-exit-when-extracting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!