python解压和压缩zip文件能力很强,主要是使用python zipfile模块来完成,来看两个例子。
1、python解压zip文档:
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()