我怎样才能避免:“ZipFile 实例没有属性 '__exit__''"提取zip文件时? [英] How can I avoid: "ZipFile instance has no attribute '__exit__''" when extracting a zip file?
问题描述
代码是:
import sys
execfile('test.py')
在 test.py 中我有:
In test.py I have:
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
The code from "test.py" works when run from python idle. I am running python v2.7.10
推荐答案
我在 python 2.7 上编写了代码,但是当我将它放在使用 2.6 的服务器上时出现此错误:
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 实例没有属性 '__exit__'
为了解决这个问题,我在这篇文章中使用了塞巴斯蒂安的回答:使 Python 2.7 代码与 Python 2.6 一起运行
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
就像他说的:
contextlib.closure 与缺少的 exit 方法完全相同ZipFile 应该做的.即调用close方法
contextlib.closing does exactly what the missing exit method on the ZipFile would be supposed to do. Namely, call the close method
这篇关于我怎样才能避免:“ZipFile 实例没有属性 '__exit__''"提取zip文件时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!