如何在所有操作系统上用Python解压缩文件?

发布于 2021-01-29 15:07:12

是否有一个简单的Python函数可以像这样解压缩.zip文件?

unzip(ZipSource, DestinationDirectory)

我需要在Windows,Mac和Linux上执行相同操作的解决方案:如果zip是文件,则始终生成文件;如果zip是目录,则始终生成目录;如果zip是多个文件,则始终生成目录。始终位于给定的目标目录内,而不是

如何在Python中解压缩文件?

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

    使用zipfile标准库中的模块:

    import zipfile,os.path
    def unzip(source_filename, dest_dir):
        with zipfile.ZipFile(source_filename) as zf:
            for member in zf.infolist():
                # Path traversal defense copied from
                # http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789
                words = member.filename.split('/')
                path = dest_dir
                for word in words[:-1]:
                    while True:
                        drive, word = os.path.splitdrive(word)
                        head, word = os.path.split(word)
                        if not drive:
                            break
                    if word in (os.curdir, os.pardir, ''):
                        continue
                    path = os.path.join(path, word)
                zf.extract(member, path)
    

    请注意,使用的时间extractall会短很多,但是该方法
    无法 防止Python
    2.7.4之前的路径遍历漏洞。如果可以保证您的代码在最新版本的Python上运行。



知识点
面圈网VIP题库

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

去下载看看