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.htmlhttp://www.php.cn/python-tutorials-394048.html
相關文章
相關標籤/搜索