首页 > 编程语言 > 详细

python zlib 压缩 解压 文件夹

时间:2015-02-04 23:11:55      阅读:409      评论:0      收藏:0      [点我收藏+]
import os,os.path
import zipfile
 
def zip_dir(dirname,zipfilename):
    filelist = []
    if os.path.isfile(dirname):
        filelist.append(dirname)
    else :
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))
         
    zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
    for tar in filelist:
        arcname = tar[len(dirname):]
        #print arcname
        zf.write(tar,arcname)
    zf.close()
 
 
def unzip_file(zipfilename, unziptodir):
    if not os.path.exists(unziptodir): os.mkdir(unziptodir, 0777)
    zfobj = zipfile.ZipFile(zipfilename)
    for name in zfobj.namelist():
        name = name.replace(‘\\‘,‘/‘)
        
        if name.endswith(‘/‘):
            os.mkdir(os.path.join(unziptodir, name))
        else:            
            ext_filename = os.path.join(unziptodir, name)
            ext_dir= os.path.dirname(ext_filename)
            if not os.path.exists(ext_dir) : os.mkdir(ext_dir,0777)
            outfile = open(ext_filename, ‘wb‘)
            outfile.write(zfobj.read(name))
            outfile.close()
 
if __name__ == ‘__main__‘:
    #zip_dir(r‘E:/test‘,r‘E:/test.zip‘)
    unzip_file(r‘E:/test.zip,r‘E:/test2‘)#确保test2文件夹存在

  

python zlib 压缩 解压 文件夹

原文:http://www.cnblogs.com/digtech/p/4273320.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!