Replace multiple lines after pattern in python?
<p>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. </p>

<p>lines.txt (input file, pattern"section 2") :</p>

<pre><code>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
</code></pre>

<p>lines_mod.txt (result with my current code) :</p>

<pre><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
</code></pre>

<p>Here is my python script:</p>

<pre><code>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
</code></pre>

<p>Thanks for help.</p>

<pre><code>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  # &lt;&lt;&lt;&lt;------- added a counter 
    for line in fin:
        if flag == 1:
            counter += 1 #&lt;&lt;&lt;&lt;-------- increasing counter by one every time it loops
            mod_line = list_of_words_to_replace[counter-1] + line.split()[-1] + '\n'  #&lt;---- 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 &gt; 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 #&lt;&lt;&lt;&lt;--------- just in case you want to find anotehr section
</code></pre>

<p>Like in the comments said. You were turning <code>flag = 0</code> 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 <code>flag = 0</code>. </p>

<p>Any other questions? </p>

python python-2.7