How to unzip file in Python on all OSes?

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.


Python 3.x use -e argument, not -h.. such as:

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

Tags:

Python

Zip