title: Inserting Line at Specified Position of a Text File
body: <p>I have a text file which looks like this:</p>
  
  <pre><code>blah blah
  foo1 bar1
  foo1 bar2
  foo1 bar3
  foo2 bar4
  foo2 bar5
  blah blah
  </code></pre>
  
  <p>Now I want to insert <code>'foo bar'</code> between <code>'foo1 bar3'</code> and <code>'foo2 bar4'</code>.</p>
  
  <p>This is how I did it:</p>
  
  <pre><code>import shutil
  
  txt = '1.txt'
  tmptxt = '1.txt.tmp'
  
  with open(tmptxt, 'w') as outfile:
      with open(txt, 'r') as infile:
          flag = 0
          for line in infile:
              if not line.startswith('foo1') and flag == 0:
                  outfile.write(line)
                  continue
              if line.startswith('foo1') and flag == 0:
                  flag = 1
                  outfile.write(line)
                  continue
              if line.startswith('foo1') and flag == 1:
                  outfile.write(line)
                  continue
              if not line.startswith('foo1') and flag == 1:
                  outfile.write('foo bar\n')
                  outfile.write(line)
                  flag = 2
                  continue
              if not line.startswith('foo1') and flag == 2:
                  outfile.write(line)
                  continue
  
  shutil.move(tmptxt, txt)
  </code></pre>
  
  <p>This works for me, but looks rather ugly.</p>