Extracting zip file contents to specific directory in Python 2.7

This is the code I am currently using to extract a zip file that lives in the same current working directory as the script. How can I specify a different directory to extract to?

The code I tried is not extracting it where I want.

import zipfile

fh = open('test.zip', 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
    outfile = open(name, 'wb')
    outfile.write('C:\\'+z.read(name))
    outfile.close()
fh.close()

I think you've just got a mixup here. Should probably be something like the following:

import zipfile

fh = open('test.zip', 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
    outpath = "C:\\"
    z.extract(name, outpath)
fh.close()

and if you just want to extract all the files:

import zipfile

with zipfile.ZipFile('test.zip', "r") as z:
    z.extractall("C:\\")

Use pip install zipfile36 for recent versions of Python

import zipfile36

I tried the other answers in this thread, but the final solution for me was simply:

zfile = zipfile.ZipFile('filename.zip')
zfile.extractall(optional_target_folder)

Look at extractall, but use it only with trustworthy zip files.


Adding to secretmike's answer above with support for python 2.6 for extracting all files.

import zipfile
import contextlib


with contextlib.closing(zipfile.ZipFile('test.zip', "r")) as z:
   z.extractall("C:\\")

If you just want to extract a zip file from the command line using Python (say because you don't have the unzip command available), then you can call the zipfile module directly

python -m zipfile -e monty.zip target-dir/

Take a look at the docs. It also supports compression and listing the contents.


Peter de Rivaz has a point in the comment above. You are going to want to have the directory in the call to open(). You are going to want to do something like this:

import zipfile
import os

os.mkdir('outdir')
fh = open('test.zip','rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
    outfile = open('outdir'+'/'+name, 'wb')
    outfile.write()
    outfile.close()
fh.close()