Import Os,os.pathimport ZipFile def zip_dir (dirname,zipfilename): FileList = [] if Os.path.isfile (dirname): F Ilelist.append (dirname) else:for root, dirs, files in Os.walk (dirname): For name in Files: Filelist.append (Os.path.join (root, name)) ZF = ZipFile. ZipFile (Zipfilename, "w", Zipfile.zlib.DEFLATED) for tar in filelist:arcname = Tar[len (dirname):] #print Arcname zf.write (Tar,arcname) zf.close () def unzip_file (Zipfilename, Unziptodir): If not os.path.exists (Unz Iptodir): Os.mkdir (Unziptodir, 0777) zfobj = ZipFile. ZipFile (zipfilename) for name in Zfobj.namelist (): name = Name.replace (' \ \ ', '/') if Name.endswith ('/'): Os.mkdir (Os.path.join (unziptodir, name)) Else:ext_filename = Os.path.join (Unziptodir, name) ext_dir= os.path.dirname (ext_filename) if not os.path.exists (Ext_dir): Os.mkdir ( ext_dir,0777) outfile = open (Ext_filename, ' WB ') Outfile.write (Zfobj.read (name)) Outfile.close () if __nam e__ = = ' __main__ ': #zip_dir (R ' e:/test ', R ' E:/test.zip ') unzip_file (R ' e:/test.zip,r ' E:/test2 ') #确保test2文件夹存在
Python zlib Compressed Unzip folder