Unzipping files in Python


Question

I read through the zipfile documentation, but couldn't understand how to unzip a file, only how to zip a file. How do I unzip all the contents of a zip file into the same directory?

1
325
7/31/2019 4:52:32 PM

Accepted Answer

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

That's pretty much it!

562
7/16/2019 2:08:06 PM

If you are using Python 3.2 or later:

import zipfile
with 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 the context manager construction.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon