Python zipfile模块(压缩、解压缩)的小例子

发布时间:2019-08-07编辑:脚本学堂
本文介绍下,一个python zipfile模块实现压缩与解压缩文件夹与文件的例子,用来学习zipfile模块的用法,非常不错,建议有需要的朋友作个参考。

本节内容:
使用python自带的zipfile模块做压缩文件夹/解压缩zip文件功能。

例子:
 

复制代码 代码示例:

#!/bin/python
#
#coding=utf-8
#使用zipfile做目录压缩,解压缩功能
#site: www.jb200.com
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:/python/learning',r'E:/python/learning/zip.zip')
    unzip_file(r'E:/python/learning/zip.zip',r'E:/python/learning2')