使Python 2.7代码与Python 2.6一起运行

发布于 2021-01-29 14:58:04

我有这个简单的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/horizo​​n/+bug/955994

但是是否可以移植上面的代码以使其与Python 2.6一起使用,并且仍然保持跨平台运行?

关注者
0
被浏览
87
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    关于什么:

    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方法



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看