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


    主要是 解决了压缩目录下 空文件夹 的压缩 和 解压缩问题

    压缩文件夹的函数:

     1 # coding:utf-8
     2 import os
     3 import zipfile
     4 
     5 def zipdir(dirToZip,savePath):
     6     if not os.path.isdir(dirToZip):
     7         raise Exception,u"zipDir Error,not a dir'%'".format(dirToZip)
     8 
     9     (saveDir,_)=os.path.split(savePath)
    10     if not os.path.isdir(saveDir):
    11         os.makedirs(saveDir)
    12 
    13     zipList = []
    14 
    15     for root,dirs,files in os.walk(dirToZip):
    16         for fileItem in files:
    17             zipList.append(os.path.join(root,fileItem))
    18         for dirItem in dirs:
    19             zipList.append(os.path.join(root,dirItem))
    20 
    21     zf = zipfile.ZipFile(savePath,'w',zipfile.ZIP_DEFLATED)
    22 
    23     for tar in zipList:
    24         if tar != dirToZip:
    25             zf.write(tar,tar.replace(dirToZip,''))
    26         else:
    27             zf.write(tar)
    28 
    29     zf.close()

    解压的函数:

     1 def unZipFile(unZipSrc,targeDir):
     2     if not os.path.isfile(unZipSrc):
     3         raise Exception,u'unZipSrc not exists:{0}'.format(unZipSrc)
     4 
     5     if not os.path.isdir(targeDir):
     6         os.makedirs(targeDir)
     7 
     8     print(u'开始解压缩文件:{0}'.format(unZipSrc))
     9 
    10     unZf = zipfile.ZipFile(unZipSrc,'r')
    11 
    12     for name in unZf.namelist() :
    13         unZfTarge = os.path.join(targeDir,name)
    14 
    15         if unZfTarge.endswith("/"):
    16             #empty dir
    17             splitDir = unZfTarge[:-1]
    18             if not os.path.exists(splitDir):
    19                 os.makedirs(splitDir)
    20         else:
    21             splitDir,_ = os.path.split(targeDir)
    22 
    23             if not os.path.exists(splitDir):
    24                 os.makedirs(splitDir)
    25 
    26             hFile = open(unZfTarge,'wb')
    27             hFile.write(unZf.read(name))
    28             hFile.close()
    29 
    30     print(u'解压缩完毕,目标文件目录:{0}'.format(targeDir))
    31 
    32     unZf.close()

    调用:

    if __name__ == '__main__':
        dirpath = os.path.abspath(u'.\new')
        savepath = os.path.abspath(u'.\new.zip')
    
    #    zipdir(dirpath,savepath)
        unZipFile(savepath,dirpath)
  • 相关阅读:
    转移到新的个人独立博客。
    hdu5618 (三维偏序,cdq分治)
    平衡树维护动态凸包
    poj1986 LCA
    hdu2586 LCA
    LCA最近公共祖先 ST+RMQ在线算法
    hdu 3401 单调队列优化DP
    【转】单调队列优化DP
    CodeForces 548D 单调栈
    hdu3530 单调队列
  • 原文地址:https://www.cnblogs.com/sixbeauty/p/4285827.html
Copyright © 2020-2023  润新知