提取 zip 文件时如何避免:“ZipFile 实例没有属性 '__exit__''”?

2023-12-19

代码是:

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

当从 python 空闲运行时,“test.py”中的代码可以工作。 我正在运行 python v2.7.10


我在 python 2.7 上编写了代码,但是当我将其放在使用 2.6 的服务器上时,出现以下错误:

AttributeError: ZipFile instance has no attribute '__exit__'

为了解决这个问题,我使用塞巴斯蒂安在这篇文章中的答案:使 Python 2.7 代码与 Python 2.6 一起运行 https://stackoverflow.com/questions/21268470/making-python-2-7-code-run-with-python-2-6/21268586#21268586

import contextlib

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

就像他说的:

contextlib.close 所做的正是所缺少的__exit__方法上 ZipFile 应该可以做到。即调用close方法

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

提取 zip 文件时如何避免:“ZipFile 实例没有属性 '__exit__''”? 的相关文章

随机推荐