Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() 
like image 707
lodkkx Avatar asked Feb 24 '12 13:02

lodkkx


People also ask

How do I unzip all files in a directory in Python?

To unzip a file in Python, use the ZipFile. extractall() method. The extractall() method takes a path, members, pwd as an argument and extracts all the contents. To work on zip files using Python, we will use an inbuilt python module called zipfile.

How do I extract text from a ZIP file in Python?

We create a ZipFile object in READ mode and name it as zip. printdir() method prints a table of contents for the archive. extractall() method will extract all the contents of the zip file to the current working directory. You can also call extract() method to extract any file by specifying its path in the zip file.


1 Answers

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 
like image 193
secretmike Avatar answered Sep 29 '22 12:09

secretmike