使用python替换来自另一个文本文件的两个字符串之间的文件中的文本

2024-09-29 22:33:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,它有很多数据和一些行作为

*PART, NAME=Part-Default
**
*NODE, NSET=ALLNODES
1,  -175.443970,    -165.165787
2,  -175.143875,    -161.285782
3,  -171.282181,    -163.266525
...
...
...
**
*ELEMENT, TYPE=CPE4R, ELSET=EB2
       1,       3,       2,       1,       4
       2,       6,       5,       2,       3

我想替换

*NODE,NSET=ALLNODES,在它之后的第一个出现的**来自另一个文件,该文件的数据格式为:只有用逗号分隔的数字!在

^{pr2}$

我可以用简单的命令读取另一个文件的所有行

file=open(fileName,'r')
for lines in file:

但找不到替代方法。有什么建议吗?在


Tags: 文件数据namenodedefaulttypeelementfile
2条回答

将文件内容读入字符串。在

with open('your_file', 'r') as f:
    contents = f.read()

获取两次出现之间的文本。在

^{pr2}$

然后更换它。在

contents = contents.replace(to_replace, 'whatever you want to replace it with')

然后你可以重写回一个文件。在

如果文本在另一个文件中,您可以使用相同的方法来查找要替换它的文本。在

(这不是顺便编译的,所以可能不完全正确)

    # if your input file is large, process it line by line:
   infh=open('NameOfFileWithLotsOfData','r')
   outfh=open('NameOfOutputFile','w')

   flag_replacing=False


   while True:
        line = infh.readline()
        if not flag_replacing:
            # only write out the line if not reading between *NODE and ** lines
            outfh.write(line)
        if line.startswith('*NODE'):
            flag_replacing=True
        if line.startswith('**'):
            if flag_replacing:
                # this is the time to insert the other file
                insertfh=open('FileToInsert','r')
                outfh.write(insertfh.read())
                flag_replacing=False

相关问题 更多 >

    热门问题