简体   繁体   中英

how to insert two lines into a file after found a word?

I have a file with the following 2 lines at multiple locations.

*Element Output, directions=YES
E, FV, MISES, PEEQ, S, TEMP, VOIDR, POR

Now I like to add the below 2 lines after the previous two lines at all the locations, could you please give me a hint how to do it? Thanks a lot.

*Element Output, POSITION=AVERAGED AT NODES, directions=YES
E, S

Thank you so much for your help. I appreicate it.

Here's a simple program to add the two lines.

line1 = '*Element Output, directions=YES'
line2 = 'E, FV, MISES, PEEQ, S, TEMP, VOIDR, POR'
add1 = '*Element Output, POSITION=AVERAGED AT NODES, directions=YES'
add2 = 'E, S'

#the below two lines will read all the lines in the file
with open("xyz.txt", "r") as f:
    x = f.readlines()

#this line will create a list. each line will be a list item
y  = [i.strip() for i in x]

#open a new file for writing. iterate thru the list
#write the two new lines if you find our two consecutive lines
#else just write the row we read
#do this until the last line on the list

with open('abc.txt','w') as f:
    i = 0
    while i < (len(y)):
        if y[i] == line1 and y[i+1] == line2:
            f.write(y[i] + '\n')
            f.write(y[i+1] + '\n')
            f.write(add1 + '\n')
            f.write(add2 + '\n')
            i+=2
        else:
            f.write(y[i] + '\n')
            i+=1

Original file:

This is first line and we shouldnt update after this line
*Element Output, directions=YES
E, FV, MISES, PEEQ, S, TEMP, VOIDR, POR
This is line 4. After inserting the two lines, this line should become line 6
This is line 5. Nothing should be added between line 4 and line 5
Same with this line 6. Nothing added between line 5 and line 6
*Element Output, directions=YES
E, FV, MISES, PEEQ, S, TEMP, VOIDR, POR
This is line 9. After processing, there should be two lines above this.
No addition between line 9 and this (line 10)

New file with updates:

This is first line and we shouldnt update after this line
*Element Output, directions=YES
E, FV, MISES, PEEQ, S, TEMP, VOIDR, POR
*Element Output, POSITION=AVERAGED AT NODES, directions=YES
E, S
This is line 4. After inserting the two lines, this line should become line 6
This is line 5. Nothing should be added between line 4 and line 5
Same with this line 6. Nothing added between line 5 and line 6
*Element Output, directions=YES
E, FV, MISES, PEEQ, S, TEMP, VOIDR, POR
*Element Output, POSITION=AVERAGED AT NODES, directions=YES
E, S
This is line 9. After processing, there should be two lines above this.
No addition between line 9 and this (line 10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM