Search code examples
pythonzip

How to unzip file in Python on all OSes?


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

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; always inside, not at, the given destination directory

How do I unzip a file in Python?


Solution

  • 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)
    

    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.