【问题标题】:Replace text in a file between two strings from another text file using python使用python替换来自另一个文本文件的两个字符串之间的文件中的文本
【发布时间】:2017-06-01 20:13:19
【问题描述】:

我有一个文件,其中包含很多数据,其中一些行为

*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

我想替换之间的文字

1,  -75.443970, -15.165787
2,  -75.143875, -11.285782
3,  -71.282181, -13.266525

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

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

但无法弄清楚替换方法。有什么建议吗?

【问题讨论】:

  • 你是说你想用另一个文件中的其他数据替换这些数据吗?
  • @IronFist,没错。从解释上看不清楚吗?

标签: python string text replace


【解决方案1】:

将文件内容读入字符串。

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

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

starting_text = 'whatever your first bound is'
ending_text = 'whatever your second bound is'
to_replace = contents[contents.find(starting_text)+len(starting_text):contents.rfind(ending_text)]

然后替换它。

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

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

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

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

【讨论】:

    【解决方案2】:
        # 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
    

    【讨论】:

    • 因为文件有多个 ** 出现,所以脚本失败。文本只能在第一次出现 ** 之前被替换
    • 您的问题不够具体...替换仅在脚本看到 *NODE 时发生。如果您只想在第一次看到 *NODE 时替换,则在脚本末尾断开并复制文件的其余部分...
    猜你喜欢
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2023-04-08
    • 2021-07-23
    • 2019-12-25
    • 2016-03-29
    相关资源
    最近更新 更多