需求
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:#直接写入原文件中(此处如何写入新文件可替换file)
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):#如果能找到插入字符串,则进行插入,找不到则返回-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)#替换