tkbx tkbx - 4 months ago 38x
Python Question

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?


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
            words = member.filename.split('/')
            path = dest_dir
            for word in words[:-1]:
                drive, word = os.path.splitdrive(word)
                head, word = os.path.split(word)
                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.