码迷,mamicode.com
首页 > 编程语言 > 详细

python zlib 压缩 解压 文件夹

时间:2015-02-04 23:14:00      阅读:299      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!