简体   繁体   English

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

[英]How to unzip file in Python on all OSes?

Is there a simple Python function that would allow unzipping a .zip file like so?:是否有一个简单的 Python 函数可以像这样解压缩 .zip 文件?:

unzip(ZipSource, DestinationDirectory)

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;我需要在 Windows、Mac 和 Linux 上执行相同操作的解决方案:如果 zip 是文件,则始终生成文件,如果 zip 是目录,则始终生成目录,如果 zip 是多个文件,则生成目录; always inside, not at, the given destination directory总是在给定的目标目录中,而不是在

How do I unzip a file in Python?如何在 Python 中解压缩文件?

Use the zipfile module in the standard library:使用标准库中的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)

Note that using extractall would be a lot shorter, but that method does not protect against path traversal vulnerabilities before Python 2.7.4.请注意,使用extractall会短得多,但该方法不能防止Python 2.7.4 之前的路径遍历漏洞 If you can guarantee that your code runs on recent versions of Python.如果你能保证你的代码在最新版本的 Python 上运行。

Python 3.x use -e argument, not -h.. such as: Python 3.x 使用 -e 参数,而不是 -h .. 例如:

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

arguments are as follows..论据如下..

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM