Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unzipping directory structure with python

Tags:

python

unzip

I have a zip file which contains the following directory structure:

dir1\dir2\dir3a dir1\dir2\dir3b 

I'm trying to unzip it and maintain the directory structure however I get the error:

IOError: [Errno 2] No such file or directory: 'C:\\\projects\\\testFolder\\\subdir\\\unzip.exe' 

where testFolder is dir1 above and subdir is dir2.

Is there a quick way of unzipping the file and maintaining the directory structure?

like image 818
Flyer1 Avatar asked Mar 12 '09 18:03

Flyer1


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 zipping and unzipping of files take place 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

The extract and extractall methods are great if you're on Python 2.6. I have to use Python 2.5 for now, so I just need to create the directories if they don't exist. You can get a listing of directories with the namelist() method. The directories will always end with a forward slash (even on Windows) e.g.,

import os, zipfile  z = zipfile.ZipFile('myfile.zip') for f in z.namelist():     if f.endswith('/'):         os.makedirs(f) 

You probably don't want to do it exactly like that (i.e., you'd probably want to extract the contents of the zip file as you iterate over the namelist), but you get the idea.

like image 104
Jeff Avatar answered Oct 04 '22 09:10

Jeff