如何在所有操作系统上用 Python 解压缩文件? [英] How to unzip file in Python on all OSes?

查看:21
本文介绍了如何在所有操作系统上用 Python 解压缩文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a simple Python function that would allow unzipping a .zip file like so?:

unzip(ZipSource, DestinationDirectory)

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

I need the solution to act the same on Windows, Mac and Linux: always produce a file if the zip is a file, directory if the zip is a directory, and directory if the zip is multiple files; always inside, not at, the given destination directory

如何在 Python 中解压文件?

How do I unzip a file in Python?

推荐答案

使用 zipfile 标准库中的模块:

Use the zipfile module in the standard library:

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 上运行.

Note that using extractall would be a lot shorter, but that method does not protect against path traversal vulnerabilities before Python 2.7.4. If you can guarantee that your code runs on recent versions of Python.

这篇关于如何在所有操作系统上用 Python 解压缩文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆