【问题标题】:How to unzip file in Python on all OSes?如何在所有操作系统上用 Python 解压缩文件?
【发布时间】:2019-11-28 04:25:32
【问题描述】:

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

unzip(ZipSource, DestinationDirectory)

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

如何在 Python 中解压缩文件?

【问题讨论】:

    标签: python zip


    【解决方案1】:

    使用标准库中的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 之前,该方法可以防止 path traversal vulnerabilities。如果您能保证您的代码在最新版本的 Python 上运行。

    【讨论】:

    • @tkbx:两者都是可能的。例如。使用绝对路径名。
    • @tkbx 已更新为安全替代方案。
    • 这似乎很奇怪,它还没有被做成 unzip() 之类的东西,甚至 zipfile.unzip() 会更好。无论如何,谢谢,这比 os.system('unzip...') 好得多,而且不支持 Windows。
    • @phihag 我使用了您发布的实现,它有一个奇怪的行为(python3.3 OSX)。它将文件提取到正确的目录中。假设文件 z.zip 包含单个文件 a/b/c.txt,此实现将该文件解压缩到 a/b/a/b/c.txt 中。在检查路径后,我可以通过 if(member.filename.split('/').pop()): member.filename = member.filename.split('/').pop() zf.extract(member, path) 解决此问题。
    • 请注意,从 Python 2.7.4 开始存在路径遍历漏洞has been fixed
    【解决方案2】:

    Python 3.x 使用 -e 参数,而不是 -h.. 如:

    python -m zipfile -e compressedfile.zip c:\output_folder
    

    参数如下..

    zipfile.py -l zipfile.zip        # Show listing of a zipfile
    zipfile.py -t zipfile.zip        # Test if a zipfile is valid
    zipfile.py -e zipfile.zip target # Extract zipfile into target dir
    zipfile.py -c zipfile.zip src ... # Create zipfile from sources
    

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 2018-06-26
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      相关资源
      最近更新 更多