""" unzip.py Version: 1.0 Extract a zipfile to the directory provided It first creates the directory structure to house the files then it extracts the files to it. Sample usage: command line unzip.py -p 10 -z c:\testfile.zip -o c:\testoutput python class import unzip un = unzip.unzip() un.extract(r'c:\testfile.zip', 'c:\testoutput') By Doug Tolton Fixed by Robert Cowham """ import sys import zipfile import os import os.path import getopt class unzip: def __init__(self, verbose = False, percent = 50): self.verbose = verbose self.percent = percent def extract(self, file, dir): if not dir.endswith(':') and not os.path.exists(dir): os.mkdir(dir) zf = zipfile.ZipFile(file) num_files = len(zf.namelist()) percent = self.percent divisions = 100 / percent perc = int(num_files / divisions) # extract files to directory structure for i, name in enumerate(zf.namelist()): if self.verbose == True: print "Extracting %s" % name elif (i % perc) == 0 and i > 0: complete = int (i / perc) * percent print "%s%% complete" % complete if not name.endswith('/'): filename = os.path.abspath(os.path.join(dir, name)) filedir = os.path.dirname(filename) if not os.path.exists(filedir): os.makedirs(filedir) outfile = open(filename, 'wb') outfile.write(zf.read(name)) outfile.flush() outfile.close() def usage(): print """usage: unzip.py -z <zipfile> -o <targetdir> <zipfile> is the source zipfile to extract <targetdir> is the target destination -z zipfile to extract -o target location -p sets the percentage notification -v sets the extraction to verbose (overrides -p) long options also work: --verbose --percent=10 --zipfile=<zipfile> --outdir=<targetdir>""" def main(): shortargs = 'vhp:z:o:' longargs = ['verbose', 'help', 'percent=', 'zipfile=', 'outdir='] unzipper = unzip() try: opts, args = getopt.getopt(sys.argv[1:], shortargs, longargs) except getopt.GetoptError: usage() sys.exit(2) zipsource = "" zipdest = "" for o, a in opts: if o in ("-v", "--verbose"): unzipper.verbose = True if o in ("-p", "--percent"): if not unzipper.verbose == True: unzipper.percent = int(a) if o in ("-z", "--zipfile"): zipsource = a if o in ("-o", "--outdir"): zipdest = a if o in ("-h", "--help"): usage() sys.exit() if zipsource == "" or zipdest == "": usage() sys.exit() unzipper.extract(zipsource, zipdest) if __name__ == '__main__': main()
# | Change | User | Description | Committed | |
---|---|---|---|---|---|
#1 | 11314 | Robert Cowham | Initial population of perforce_software version of P4OFC | ||
//guest/robert_cowham/perforce/P4OFC/main/test/unzip.py | |||||
#1 | 10843 | Robert Cowham |
Initial version of P4OFC source code. See README.txt (and LICENSE.txt and doc\P4OFC-Design.docx) |