Python压缩和解压缩实践

工作需要,将已经打好的war包解压出来,重新压缩WEB-INF中的classes文件夹到WEB-INF.zip

那就只好从实际出发,用代码来了解一下python的压缩解压缩了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/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