3
By Doug Tolton (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252508)
13
Extract a zipfile to the directory provided
14
It first creates the directory structure to house the files
15
then it extracts the files to it.
19
un.extract(r'c:\testfile.zip', 'c:\testoutput')
21
By Doug Tolton (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252508)
23
def __init__(self, verbose = True, percent = 10):
24
self.verbose = verbose
25
self.percent = percent
27
def extract(self, file, dir):
28
if not dir.endswith(':') and not os.path.exists(dir):
31
zf = zipfile.ZipFile(file)
33
# create directory structure to house files
34
#print "Creating plugin structure:"
35
self._createstructure(file, dir)
37
num_files = len(zf.namelist())
38
percent = self.percent
39
divisions = 100 / percent
40
perc = int(num_files / divisions)
42
# extract files to directory structure
43
for i, name in enumerate(zf.namelist()):
45
if self.verbose == True:
47
#print "Extracting %s" % name
48
elif perc > 0 and (i % perc) == 0 and i > 0:
49
complete = int (i / perc) * percent
50
#print "%s%% complete" % complete
52
if not name.endswith('/'):
53
outfile = open(os.path.join(dir, name), 'wb')
54
outfile.write(zf.read(name))
58
def _createstructure(self, file, dir):
59
self._makedirs(self._listdirs(file), dir)
61
def _makedirs(self, directories, basedir):
62
""" Create any directories that don't currently exist """
63
#print "Processing directories contained in the zip file: %s" % directories
64
for dir in directories:
65
curdir = os.path.join(basedir, dir)
67
curdir = os.path.normpath(curdir)
68
#print "Checking to see if we should create %s" % curdir
69
if not os.path.exists(curdir):
70
# use makedirs to create parent directories as well
71
#print "Creating %s" % curdir
74
def _listdirs(self, file):
75
""" Grabs all the directories in the zip structure
76
This is necessary to create the structure before trying
77
to extract the file to it. """
78
zf = zipfile.ZipFile(file)
82
for name in zf.namelist():
83
(path, filename) = os.path.split(name)