我有这个简单的python函数,可以提取一个zip文件(与平台无关)
def unzip(source, target): with zipfile.ZipFile(source , "r") as z: z.extractall(target) print "Extracted : " + source + " to: " + target
这在Python 2.7上运行良好,但在Python 2.6上失败:
AttributeError: ZipFile instance has no attribute '__exit__':
我发现此建议要求升级2.6-> 2.7 https://bugs.launchpad.net/horizon/+bug/955994
但是是否可以移植上面的代码以使其与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方法
contextlib.closing
__exit__
ZipFile
close