defpprintdir(self): """Print a table of contents of the zip files more elegantly.""" self.print_bold('Archive: ' + os.path.basename(self.filename)) ifself.comment: self.print_bold('Comment: ' + self.comment.decode('gb18030')) print('{:^10} {:^19} {}'.format('Size', 'Modified', 'File Name')) print('{:=^10} {:=^19} {:=<11}'.format('', '', '')) size_sum = 0 for zinfo inself.filelist: filename = zinfo.filename filetime = '{:%Y-%m-%d %H:%M:%S}'.format( datetime.datetime(*zinfo.date_time)) print('{:>10} {} {}'.format(zinfo.file_size, filetime, filename)) size_sum += zinfo.file_size file_sum = len(self.filelist) print('{:-^10} {:^19} {:-^11}'.format('', '', '')) print('{:>10} {:^19} {}'.format(str(size_sum), '', str(file_sum) + ' files'))
defcenc(name): """Check if it's not None and encode.""" return name isnotNoneand name.encode() orNone
classMyParser(argparse.ArgumentParser): """Paring command line options.""" def__init__(self, prog=None): description = 'Extract files from zipfiles using encoding GBK' super().__init__(prog=prog, description=description) self.add_argument('zipfile', nargs='+') self.add_argument('-l', '--list', action='store_true', dest='islist', help='list files in zipfiles') self.add_argument('-o', '--outdir', dest='outdir', help='set output directory') self.add_argument('-p', '--password', dest='password', help='set password')
defmain(): """Parse argument, list or extract zip files.""" myparser = MyParser() args = myparser.parse_args()
if args.islist: for zfile in args.zipfile: with GBKZipFile(zfile) as zfp: if args.password: zfp.setpassword(cenc(args.password)) zfp.pprintdir() else: for zfile in args.zipfile: with GBKZipFile(zfile) as zfp: zfp.extractall(path=args.outdir, pwd=cenc(args.password))
for opt, value in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-l", "--list"): global IFLIST IFLIST = True elif opt in ("-o", "--outdir"): outdir = value.decode('utf8') elif opt in ("-p", "--password"): password = value
return outdir, password, zipfiles
deflistzip(filename, password=None): """列出文件内容""" print("Archive: " + filename) with ZipFile(filename, 'r') as infile: if password: infile.setpassword(password)
for name in infile.namelist(): utf8name = name.decode('gbk') print(utf8name)
defunzip(filename, outdir='', password=None): """解压文件""" print("Unziping " + filename) with ZipFile(filename, "r") as infile: if password: infile.setpassword(password)
for name in infile.namelist(): utf8name = name.decode('gbk') print("Extracting " + utf8name) pathname = os.path.join(outdir, os.path.dirname(utf8name)) targetname = os.path.join(outdir, utf8name) ifnot os.path.exists(pathname): os.makedirs(pathname) data = infile.read(name) ifnot os.path.exists(targetname): withopen(targetname, 'w') as myfile: myfile.write(data)