簡體   English   中英

使用 python 從另一個文本文件中的兩個字符串之間替換文件中的文本

[英]Replace text in a file between two strings from another text file using 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 之后第一次出現 ** 來自另一個文件,該文件具有以下形式的數據,即只有用逗號分隔的數字!

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

我可以使用簡單的命令讀取另一個文件的所有行

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

但無法弄清楚更換方法。 有什么建議?

將文件的內容讀入一個字符串。

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')

然后你可以將它重寫回一個文件。

如果文本位於另一個文件中,您可以使用相同的方法查找要替換的文本。

(這不是順便編譯的,所以它可能不完全正確)

    # 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM