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

python的zipfile实现文件目录解压缩

2015-02-11 12:13 609 查看
主要是 解决了压缩目录下 空文件夹 的压缩 和 解压缩问题

压缩文件夹的函数:

# coding:utf-8
import os
import zipfile

def zipdir(dirToZip,savePath):
if not os.path.isdir(dirToZip):
raise Exception,u"zipDir Error,not a dir'%'".format(dirToZip)

(saveDir,_)=os.path.split(savePath)
if not os.path.isdir(saveDir):
os.makedirs(saveDir)

zipList = []

for root,dirs,files in os.walk(dirToZip):
for fileItem in files:
zipList.append(os.path.join(root,fileItem))
for dirItem in dirs:
zipList.append(os.path.join(root,dirItem))

zf = zipfile.ZipFile(savePath,'w',zipfile.ZIP_DEFLATED)

for tar in zipList:
if tar != dirToZip:
zf.write(tar,tar.replace(dirToZip,''))
else:
zf.write(tar)

zf.close()


解压的函数:

def unZipFile(unZipSrc,targeDir):
if not os.path.isfile(unZipSrc):
raise Exception,u'unZipSrc not exists:{0}'.format(unZipSrc)

if not os.path.isdir(targeDir):
os.makedirs(targeDir)

print(u'开始解压缩文件:{0}'.format(unZipSrc))

unZf = zipfile.ZipFile(unZipSrc,'r')

for name in unZf.namelist() :
unZfTarge = os.path.join(targeDir,name)

if unZfTarge.endswith("/"):
#empty dir
splitDir = unZfTarge[:-1]
if not os.path.exists(splitDir):
os.makedirs(splitDir)
else:
splitDir,_ = os.path.split(targeDir)

if not os.path.exists(splitDir):
os.makedirs(splitDir)

hFile = open(unZfTarge,'wb')
hFile.write(unZf.read(name))
hFile.close()

print(u'解压缩完毕,目标文件目录:{0}'.format(targeDir))

unZf.close()


调用:

if __name__ == '__main__':
dirpath = os.path.abspath(u'.\\new')
savepath = os.path.abspath(u'.\\new.zip')

#    zipdir(dirpath,savepath)
unZipFile(savepath,dirpath)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: