您的位置:首页 > 编程语言 > Python开发

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

2010-06-19 10:26 861 查看
'''

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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐