zipfile的重新封装

#  -*- coding: utf-8 -*-

import  zipfile, os

class  ZFile(zipfile.ZipFile):
    
def   __init__ (self, file, mode = ' r ' , compression = 0):
        zipfile.ZipFile.
__init__ (self, file, mode, compression)

    
def  extract(self, dir = '' ):
        
for  f  in  self.namelist():
            path 
=  os.path.join(os.path.abspath(dir), f)
            
if   not  os.path.exists(os.path.dirname(path)):
                os.mkdir(os.path.dirname(path))
            
if   not  path.endswith( ' / ' ):
                file(path, 
' wb ' ).write(self.read(f))

    
def  writedir(self, dir):
        dir 
=  os.path.abspath(dir)
        empty 
=  []       # the list of the path without file in
         for  root, dirs, files  in  os.walk(dir):
            
if   not  (files  and  dirs):
                zipinfo 
=  zipfile.ZipInfo(root.replace(dir + os.sep,  '' ) + os.sep)
                empty.append(zipinfo)
            
for  f  in  files:
                path 
=  os.path.join(root, f)
                
print   " compressing " ,path
                self.write(path, path.replace(dir
+ os.sep,  '' ))
        
for  f  in  empty:
            
print   " compressing " ,f.filename
            self.writestr(f, 
'' )

测试代码:

=  ZFile( ' other.zip ' ' w ' , zipfile.ZIP_DEFLATED)
z.writedir(
' other ' )
z.close()

other是个目录,里面还有文件、子目录和空的子目录。执行后,压缩包维持了原本的目录结构。

你可能感兴趣的:(File,测试,Path,compression)