Unzipping files in Python Unzipping files in Python python python

Unzipping files in Python


import zipfilewith zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:    zip_ref.extractall(directory_to_extract_to)

That's pretty much it!


If you are using Python 3.2 or later:

import zipfilewith zipfile.ZipFile("file.zip","r") as zip_ref:    zip_ref.extractall("targetdir")

You dont need to use the close or try/catch with this as it uses thecontext manager construction.


zipfile is a somewhat low-level library. Unless you need the specifics that it provides, you can get away with shutil's higher-level functions make_archive and unpack_archive.

make_archive is already described in this answer. As for unpack_archive:

import shutilshutil.unpack_archive(filename, extract_dir)

unpack_archive detects the compression format automatically from the "extension" of filename (.zip, .tar.gz, etc), and so does make_archive. Also, filename and extract_dir can be any path-like objects (e.g. pathlib.Path instances) since Python 3.7.