一个修改过的python zifile的包装模块,支持对目录压缩(包括空的文件夹),解压缩会解压缩空目录

'''

Created on 2010-5-26

 

@author: sean_long

'''

import os;

import zipfile

import os.path

 

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)

            fd=file(f, 'wb');

            fd.write(self.zfile.read(filename));

            fd.close(); 

        else:

            d=os.path.join(path,filename);

            if not os.path.exists(d):

                os.makedirs(d);           

 

 

def zipFolder(z,folderPath,basePath):

    ar=os.listdir(folderPath);

    for item in ar:

        abtPath=os.path.join(folderPath,item);

        bsPath=os.path.join(basePath,item);

        if(os.path.isdir(abtPath)):

            if(os.listdir(abtPath)==[]):

                zif=zipfile.ZipInfo(bsPath+"/");

                z.writestr(zif,"");

            else:

                zipFolder(z,abtPath,bsPath)

        else:

            z.write(abtPath,bsPath);

 

 

 

def createfolderZip(filePath,folderPath):

    z=zipfile.ZipFile(filePath,"w",zipfile.ZIP_DEFLATED);

    basePath=os.path.basename(folderPath);

    zipFolder(z,folderPath,basePath);

    z.close();

 

def extractZip(zfile, path):

    z = ZFile(zfile)

    z.extract_to(path)

    z.close()

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值