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

2024-10-01 02:21:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

unzip(ZipSource, DestinationDirectory)

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

如何用Python解压文件?


Tags: 文件函数目录linuxwindowsmaczip解决方案
2条回答

使用标准库中的^{}模块:

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)

注意,使用^{}要短得多,但是在Python 2.7.4之前,该方法不会对path traversal vulnerabilities进行保护。如果你能保证你的代码运行在最新版本的Python上。

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

相关问题 更多 >