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>

<p>You need to revisit your flag update criteria to match the expected output.</p>

<p>Since you set <code>flag = 1</code> for the <code>if line.find('section 2') != -1</code> condition, it will modify only one line following the matched line.</p>

<p>Since you mention you want to replace more lines, you can probably add a counter that tracks the number of lines you've modified since <code>flag = 1</code>... and when you hit the desired number of lines, then reset <code>flag = 0</code>.</p>

<pre><code>count = 0

for line in fin:
    if flag == 1 and count &lt; 3:
        mod_line = 'mod ' + line.split()[-1] + '\n'
        count += 1
        fout.write(mod_line)
        continue
</code></pre>

python python-2.7