python文件压缩例子,python压缩与解压缩zip文件

发布时间:2019-11-19编辑:脚本学堂
如何用Python压缩与解压缩zip文件,python使用zipfile模块实现文档与文件夹压缩解压缩的例子。

python解压和压缩zip文件能力很强,主要是使用python zipfile模块来完成,来看两个例子。

1、python解压zip文档:
 

复制代码 代码示例:
#/usr/bin/python
#coding=utf-8
import os,sys,time
import zipfile
filename = 'callofdutyblackopszombies_1349649132343_my.zip'  #要解压的文件
filedir = 'data/'  #解压后放入的目录
r = zipfile.is_zipfile(filename)
if r:
    starttime = time.time()
    fz = zipfile.ZipFile(filename,'r')
    for file in fz.namelist():
        print(file)  #打印zip归档中目录
        fz.extract(file,filedir)
    endtime = time.time()
    times = endtime - starttime
else:
    print('This file is not zip file')
print('times' + str(times))

2、python压缩文件夹为zip
 

复制代码 代码示例:

#/usr/bin/python
#coding=utf-8

import os
import zipfile
import sys
try:
    import zlib
    compression = zipfile.ZIP_DEFLATED
except:
    compression = zipfile.ZIP_STORED
path = 'data/'  #要进行压缩的文档目录
start = path.rfind(os.sep) + 1
filename = 'callofdutyblackopszombies_1349649132343_my.zip'  #压缩后的文件名
z = zipfile.ZipFile(filename,mode = "w",compression = compression)
try:
    for dirpath,dirs,files in os.walk(path):
        for file in files:
            if file == filename or file == "zip.py":
                continue
            print(file)
            z_path = os.path.join(dirpath,file)
            z.write(z_path,z_path[start:])
    z.close()
except:
    if z:
        z.close()