需求
1. C60Gs.inp: 改变之后的inp文件
2. C60Gs-nochange.inp: 改变之前的inp文件
3. cohesive_element.txt:其中的内容会插入到inp中,*End Part前
4. the cohesive properties-1.txt: 其中的内容会替换.inp中的:
*Element, type=COH2D4
5. the cohesive properties-2.txt: 其中的内容会替换.inp中的:
**
** OUTPUT REQUESTS
**
*Restart, write, frequency=0
**
** FIELD OUTPUT: F-Output-1
**
*Output, field, variable=PRESELECT
**
** HISTORY OUTPUT: H-Output-1
**
*Output, history, variable=PRESELECT
思考
- 采用Python的文件读取进行文件的读取
- 采用正则来匹配文本数据
- 利用文件夹os操作实现批处理
代码
import re
import os
def updateFile(file,sub_file,old_str):
"""
:param file: 操作源文件位置
:param sub_file: 替换源文件位置
:param old_str: 待替换的符串
:return: 返回替换后的源文件
"""
file_data = ""
with open(file,"r") as f:
for line in f:
file_data += line
if(re.search(old_str,file_data).start() == -1):
print("找不到该字符串,替换失败")
else:
file_data1 = ""
with open(sub_file, "r") as f:
for line in f:
file_data1 += line
file_data= re.sub(old_str,file_data1,file_data)
with open(file,"w") as f:
f.write(file_data)
print("替换成功")
def insertFile(file,insert_file,insert_word):
"""
:param file: 源文件位置
:param insert_file: 插入文件位置
:param insert_word: 定位插入字符串
:return: 返回插入后的源文件
"""
with open(file,"r") as f:
file_data = ""
for line in f:
file_data += line
tab = re.search(insert_word,file_data)
pos = tab.start()
if(pos != -1):
with open(insert_file,"r") as f:
file_data1 = ""
for line in f:
file_data1 += line
content = file_data[:pos]+ file_data1 +file_data[pos:]
with open(file, "w") as f:
f.write(content)
print("插入成功")
else:
print("找不到该位置,插入失败")
older_str1 ="\*Element, type=COH2D4"
older_str2 = "(\*)*(\s)*(\*)*\sOUTPUT REQUESTS(.|\n)*variable=PRESELECT"
path_orginal = r"F:\work\find and sub2\orginal_file"
path_sub = r"F:\work\find and sub2\sub_file"
files_orginal = os.listdir(path_orginal)
files_sub = os.listdir(path_sub)
for file in zip(files_orginal,files_sub):
org_position = path_orginal + "\\" +file[0]
org_sub = path_sub + "\\" +file[1]
updateFile(org_position,org_sub,older_str2)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现