工作需要,将已经打好的war包解压出来,重新压缩WEB-INF中的classes文件夹到WEB-INF.zip
那就只好从实际出发,用代码来了解一下python的压缩解压缩了。
#!/usr/bin/env python
# encoding: utf-8
"""
@version: 1.0
@author: jiangmtiao
@site: my.oschina.net/jiangmitiao/blog
@software: PyCharm
@file: autoPackage.py
@time: 2016/3/23 9:42
@description: TODO
"""
import os
import zipfile
class AutoPackage(object):
def __init__(self, mavenPath="auto", projectPath="./"):
self.mavenPath = mavenPath
self.projectPath = projectPath
self.fileName = None
pass
def check(self):
# 检查是否有war文件,不存在则退出
tmpPath = os.path.join(self.projectPath, 'target/')
if not os.path.exists(tmpPath):
print "no target"
exit(-1)
pass
for fn in os.listdir(os.path.join(self.projectPath, 'target/')):
if fn.endswith(".war"):
self.fileName = fn
break
pass
pass
if self.fileName is None:
print " no *.war"
exit(-1)
pass
pass
def package(self):
tmpPath = self.projectPath + 'target/'
# 解压指定的文件
zipFile = zipfile.ZipFile(os.path.join(tmpPath, self.fileName))
for f in zipFile.namelist():
if f.find("classes/com") > 0:
zipFile.extract(f, tmpPath)
pass
pass
# 准备压缩文件
zpfd = zipfile.ZipFile(tmpPath + "/WEB-INF.zip", mode='w')
for dirpath, dirnames, filenames in os.walk(tmpPath + "/WEB-INF"):
for filename in filenames:
#oldFilename是相对路径或者绝对路径
oldFilename = os.path.join(dirpath, filename)
#zipFileName是打入压缩包中的文件路径
zipFileName = dirpath.replace(tmpPath + "/WEB-INF\\", "") + "/" + filename
zpfd.write(oldFilename, zipFileName)
pass
pass
zpfd.close()
pass
if __name__ == '__main__':
auto = AutoPackage(projectPath="D:/idea/work/api/")
# auto = AutoPackage()
auto.check()
auto.package()
pass