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

tkb*_*kbx 26 python zip

有一个简单的Python函数可以解压缩.zip文件吗?:

unzip(ZipSource, DestinationDirectory)
Run Code Online (Sandbox Code Playgroud)

我需要解决方案在Windows,Mac和Linux上采取相同的行动:如果zip是文件,则始终生成文件;如果zip是目录,则始终生成目录;如果zip是多个文件,则生成目录; 总是在给定目标目录内,而不是在给定目标目录中

如何在Python中解压缩文件?

phi*_*hag 44

使用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)
Run Code Online (Sandbox Code Playgroud)

请注意,使用extractall会更短,但该方法不能防止Python 2.7.4之前的路径遍历漏洞.如果您可以保证您的代码在最新版本的Python上运行.

  • 请注意,从Python 2.7.4开始,路径遍历漏洞[已得到修复](http://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.extract). (9认同)
  • @phihag我使用了你发布的实现,它有一个奇怪的行为(python3.3 OSX).它将文件解压缩到正确的目录中.假设文件z.zip包含单个文件a/b/c.txt,此实现将该文件解压缩到/ b/a/b/c.txt中.我能够通过`if(member.filename.split('/').pop())来解决这个问题:member.filename = member.filename.split('/').pop()zf.extract(成员) ,路径)`检查路径后. (3认同)