python文件压缩代码实例

发布时间:2020-06-19编辑:脚本学堂
本文介绍了python实现文件压缩的一个小例子,python文件压缩实例代码,有需要的朋友参考下。

很久以前写的python对文件的压缩操作,可以参考下,下面是完整代码。

例子:
 

复制代码 代码示例:
'''
Created on 2011-8-7
#site www.jb200.com
@author: WGY
'''
import zipfile
import os.path
import os
class ZFile(object):
    def __init__(self, filename, mode='r', basedir=''):
        self.filename = filename
        self.mode = mode
        if self.mode in ('w', 'a'):
            self.zfile = zipfile.ZipFile(filename, self.mode, compression=zipfile.ZIP_DEFLATED)
        else:
            self.zfile = zipfile.ZipFile(filename, self.mode)
        self.basedir = basedir
        if not self.basedir:
            self.basedir = os.path.dirname(filename)
        
    def addfile(self, path, arcname=None):
        path = path.replace('', '/')
        if not arcname:
            if path.startswith(self.basedir):
                arcname = path[len(self.basedir):]
            else:
                arcname = ''
        self.zfile.write(path, arcname)
            
    def addfiles(self, paths):
        for path in paths:
            if isinstance(path, tuple):
                self.addfile(*path)
            else:
                self.addfile(path)
            
    def close(self):
        self.zfile.close()
        
    def extract_to(self, path):
        for p in self.zfile.namelist():
            self.extract(p, path)
            
    def extract(self, filename, path):
        if not filename.endswith('/'):
            f = os.path.join(path, filename)
            dir = os.path.dirname(f)
            if not os.path.exists(dir):
                os.makedirs(dir)
            file(f, 'wb').write(self.zfile.read(filename))
        
def create(zfile, files):
    z = ZFile(zfile, 'w')
    z.addfiles(files)
    z.close()
    
def extract(zfile, path):
    z = ZFile(zfile)
    z.extract_to(path)
    z.close()
create('e:/js/a.zip',('e:/js/test.txt'))