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

如何在所有操作系统上用Python解压文件?,python,zip,Python,Zip,有没有一个简单的Python函数可以像这样解压.zip文件 unzip(ZipSource, DestinationDirectory) 我需要在Windows、Mac和Linux上采取相同的解决方案:如果zip是文件,则始终生成一个文件;如果zip是目录,则生成目录;如果zip是多个文件,则生成目录;始终在给定的目标目录中,而不是在指定的目标目录中 如何用Python解压文件?使用标准库中的模块: import zipfile,os.path def unzip(source_filenam

有没有一个简单的Python函数可以像这样解压.zip文件

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

如何用Python解压文件?

使用标准库中的模块:

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之前的版本提供保护。如果可以保证代码在最新版本的Python上运行。

Python3.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

@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开始,路径遍历漏洞就存在。