我试图在一个文件中读取和写入两个关键字之间的内容,以删除我不需要的文件的其余部分。
** ASSEMBLY
**
*Assembly, name=Assembly
**
*Instance, name=Part-1-1, part=Part-1
*Node
**Node
1, 12., 0.
2, 12., -6.
3, 9., -15.
4, 7.99721575, -53.
** Section: t3
*Shell Section, elset=Set-3, material=PET
2., 5
** Section: t4
*Shell Section, elset=Set-4, material=PET
2., 5
*End Instance
**
*End Assembly
**
** MATERIALS
**
*Material, name=PET我想要读的文件在上面,中间部分被剪掉了。我使用的代码是;
inFile = open("Exp_1.inp")
outFile = open("Exp_12.inp", "w")
keepCurrentSet = False
for line in inFile:
if line.startswith("*Node"):
keepCurrentSet = False
if keepCurrentSet:
outFile.write(line)
if line.startswith("*End instance"):
keepCurrentSet = True
inFile.close()
outFile.close()虽然我不知道它为什么要写一个空白文件。
编辑
inFile = open("Exp_1.inp")
outFile = open("Exp_12.inp", "w")
keepCurrentSet = True
for line in inFile:
if line.startswith("*Node"):
keepCurrentSet = True
if keepCurrentSet:
outFile.write(line)
if line.startswith("*End Instance"):
keepCurrentSet = False
inFile.close()
outFile.close()上面的代码是我所需要的解决方案。有人能建议我如何编辑这段代码,使其不包含最后的关键字“*End Instance”吗?
提前谢谢。
发布于 2019-12-04 13:03:50
稍微调试一下就可以看到两件事:
keepCurrentSet最初被设置为False (可能是True)if line.startswith("*End instance"):应该是if line.startswith("*End Instance"):发布于 2019-12-04 13:18:55
您可能不会选择此解决方案,但我将使用regex,因为它应该为您工作。使用regex,您可以将代码减少到以下几个方面:
import re
with open("Exp_1.inp") as f:
with open("Exp_12.inp", "w") as x:
x.write(re.sub("\*\*Node[\s\S]*?(?=\*End Instance)", "", f.read()))在这里,它替换了以**Node开头的所有内容,直到它到达End Instance为止。您可以检查regex表达式这里,以更好地理解该解决方案。
输出:
** ASSEMBLY
**
*Assembly, name=Assembly
**
*Instance, name=Part-1-1, part=Part-1
*Node
*End Instance
**
*End Assembly
**
** MATERIALS
**
*Material, name=PET发布于 2019-12-04 13:10:46
你几乎是对的,但你犯了两个错误:
第一次遇到*Node时,应该将keepCurrentSet设置为True,以便在输出文件中得到以下行:
if line.startswith("*Node"):
keepCurrentSet = True第二,您有一个错误:"*End instance"应该是"*End Instance"
这会让你:
inFile = open("Exp_1.inp")
outFile = open("Exp_12.inp", "w")
keepCurrentSet = False
for line in inFile:
if line.startswith("*Node"):
keepCurrentSet = True # CHANGE HERE False => True
if keepCurrentSet:
outFile.write(line)
if line.startswith("*End Instance"): # CHANGE HERE instance => Instance
keepCurrentSet = True
inFile.close()
outFile.close()https://stackoverflow.com/questions/59176455
复制相似问题