Tian Tian - 2 months ago 9
Python Question

Replace multiple lines after pattern in python?

I want to write a python script to replace first word in multiple lines after my pattern, by now I can only replace 1 line after my pattern, how can it replace more lines? Let's say 3 lines.

lines.txt (input file, pattern"section 2") :

section 1
line 1
line 2
line 3
line 4
endsection
section 2
line 1
line 2
line 3
line 4
endsection
section 3
line 1
line 2
line 3
line 4
endsection


lines_mod.txt (result with my current code) :

section 1
line 1
line 2
line 3
line 4
endsection
section 2
mod 1
line 2
line 3
line 4
endsection
section 3
line 1
line 2
line 3
line 4
endsection


Here is my python script:

with open('E:/lines.txt') as fin, open('E:/lines_m.txt', 'w') as fout:
flag = 0
for line in fin:
if flag == 1:
mod_line = 'mod ' + line.split()[-1] + '\n'
fout.write(mod_line)
flag = 0
continue
fout.write(line)
if line.find('section 2') != -1:
flag = 1


Thanks for help.

Answer
list_of_words_to_replace = ['mod','apple','xxx']
with open('E:/lines.txt') as fin, open('E:/lines_mod.txt', 'w') as fout:
    flag = 0
    counter = 0  # <<<<------- added a counter 
    for line in fin:
        if flag == 1:
            counter += 1 #<<<<-------- increasing counter by one every time it loops
            mod_line = list_of_words_to_replace[counter-1] + line.split()[-1] + '\n'  #<---- changed 'mod' to a list of words to replaced.... yes  I know it's counter - 1 because we made counter start at 1 before counting and list index starts at 0 
            fout.write(mod_line)
            if counter > 3: #replaces 3 lines you can replace the number 3 with however many lines you want to override. 
                flag = 0
            continue
        fout.write(line)
        if line.find('section 2') != -1:
            flag = 1
            counter = 0 #<<<<--------- just in case you want to find anotehr section

Like in the comments said. You were turning flag = 0 after one writeline, so we now have a counter that counts how many lines you want to write and when it goes over it sets flag = 0.

Any other questions?