编程语言
首页 > 编程语言> > python替换jar包(zip)中的文件

python替换jar包(zip)中的文件

作者:互联网

import zipfile
import os
import shutil
import time

filename = "C:\Users\ssb\Desktop\yufabu_tmp\ibt-1.1.0-REALEASE.jar" # 待解压文件,zip解压同样适用于jar!!!划重点
path2 = "C:\Users\ssb\Desktop\yufabu_tmp\ibt-1.1.0-REALEASE" # 解压路径

fz = zipfile.ZipFile(filename, 'r')
for file in fz.namelist():
fz.extract(file, path2)

# 删除删除main.ftl文件
delete_filename = 'C:\Users\ssb\Desktop\yufabu_tmp\ibt-1.1.0-REALEASE\\freemarker\main.ftl'
if os.path.exists(delete_filename):
os.remove(delete_filename)
# time.sleep(60)
# shutil.copy(文件的路径,另一个目录);拷贝main.ftl到准备压缩的目录下
shutil.copy('C:\Users\ssb\Desktop\yufabu_tmp\main.ftl', 'C:\Users\ssb\Desktop\yufabu_tmp\ibt-1.1.0-REALEASE\\freemarker\\')
print time.ctime(os.stat('C:\Users\ssb\Desktop\yufabu_tmp\ibt-1.1.0-REALEASE\\freemarker\main.ftl').st_mtime)

# 压缩回去
startdir = "C:\Users\ssb\Desktop\yufabu_tmp\ibt-1.1.0-REALEASE" # 要压缩的文件夹路径
file_news = startdir+'.jar' # 压缩后文件夹的名字
z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED) # 参数一:文件夹名
for dirpath, dirnames, filenames in os.walk(startdir): # os.walk 遍历目录
fpath = dirpath.replace(startdir, '') # 这一句很重要,不replace的话,就从根目录开始复制
fpath = fpath and fpath + os.sep or '' # os.sep路径分隔符
for filename in filenames:
z.write(os.path.join(dirpath, filename), fpath+filename)
# os.path.join()函数用于路径拼接文件路径。
# os.path.split(path)把path分为目录和文件两个部分,以列表返回
print '压缩成功'
z.close()

借鉴网址:
https://www.cnblogs.com/pipihaoke/p/8033844.html
http://www.php.cn/python-tutorials-394048.html

标签:tmp,yufabu,zip,python,jar,Desktop,filename,os,ssb
来源: https://www.cnblogs.com/sunmoon1993/p/10411345.html