The main problem is to solve the compression and decompression of empty folders in compressed directory.
Functions for compressing folders:
1# coding:utf-82 Import OS3 Import ZipFile4 5 def zipdir (dirtozip,savepath):6 ifNot Os.path.isdir (dirtozip):7Raise Exception,u"zipdir error,not a dir '% '". Format (dirtozip)8 9(savedir,_) =os.path.split (Savepath)Ten ifNot Os.path.isdir (savedir): One os.makedirs (Savedir) A -Ziplist = [] - the forRoot,dirs,filesinchOs.walk (dirtozip): - forFileiteminchFiles: - ziplist.append (Os.path.join (root,fileitem)) - forDiriteminchdirs: + ziplist.append (Os.path.join (root,diritem)) - +ZF = ZipFile. ZipFile (Savepath,'W', ZipFile. zip_deflated) A at forTarinchziplist: - ifTar! =Dirtozip: -Zf.write (Tar,tar.replace (Dirtozip,"')) - Else: - zf.write (TAR) - inZf.close ()
Decompression function:
1 def unzipfile (unzipsrc,targedir):2 ifNot Os.path.isfile (UNZIPSRC):3Raise Exception,u'unzipsrc not exists:{0}'. Format (UNZIPSRC)4 5 ifNot Os.path.isdir (targedir):6 os.makedirs (Targedir)7 8Print (U'Start extracting file: {0}'. Format (UNZIPSRC))9 TenUNZF = ZipFile. ZipFile (UNZIPSRC,'R') One A forNameinchunzf.namelist (): -Unzftarge =Os.path.join (targedir,name) - the ifUnzftarge.endswith ("/"): - #empty dir -Splitdir = unzftarge[:-1] - ifNot os.path.exists (splitdir): + os.makedirs (Splitdir) - Else: +Splitdir,_ =os.path.split (Targedir) A at ifNot os.path.exists (splitdir): - os.makedirs (Splitdir) - -hfile = open (Unzftarge,'WB') - Hfile.write (Unzf.read (name)) - hfile.close () in -Print (U'decompression complete, target file directory: {0}'. Format (targedir)) to +Unzf.close ()
Call:
if ' __main__ ' : = Os.path.abspath (U'. \\new') = Os.path.abspath (u'. \ \) New.zip') # Zipdir (Dirpath,savepath) unzipfile (Savepath,dirpath)
Python's ZipFile implementation file directory decompression