title: Inserting lines to a file after a string match
body: <p>I'm trying to search for a substring within lines of a file and insert similar lines immediately after the found line. Although there were similar solutions using the <code>fileinput</code> method, I could not figure out how to use it in my case.</p>
  
  <p>Here is what I have tried:</p>
  
  <pre><code>list = ["abc", "pqr", "xyz"]
  
  inputfile = open (somefile.txt, 'a+')
  for line in &lt;inputfile&gt;:    
      if 'stringstosearch' in line:
         for &lt;item&gt; in list:
                 new_line = "new_line with %s" %(item)        
                 inputfile.write(new_line + "\n") 
      break
  inputfile.close()
  </code></pre>
  
  <p>for example if the text file is:</p>
  
  <blockquote>
    <p>Torquent scelerisque aptent hac rhoncus vel<br>
    Turpis vestibulum tellus laoreet mollis conubia facilisis tempor nec semper<br>
    In mi mauris etiam quisque sem congue est velit lacus convallis amet ante ad<br>
    Integer maecenas semper quisque nisi hendrerit, libero feugiat cursus euismod accumsan<br>
    Dui sed magna vivamus augue ac quisque ac mauris torquent eros taciti<br>
    Conubia curae vel himenaeos dictumst sed at  </p>
  </blockquote>
  
  <pre><code>string to search = "mauris etiam quisque"
  list = ["abc", "pqr", "xyz" ]
  </code></pre>
  
  <p>Expected output after file write:</p>
  
  <blockquote>
    <p>Torquent scelerisque aptent hac rhoncus vel<br>
    Turpis vestibulum tellus laoreet mollis conubia facilisis tempor nec semper<br>
    In mi mauris etiam quisque sem congue est velit lacus convallis amet ante ad<br>
    new_line with abc<br>
    new_line with pqr<br>
    new_line with xyz<br>
    Integer maecenas semper quisque nisi hendrerit, libero feugiat cursus euismod accumsan<br>
    Dui sed magna vivamus augue ac quisque ac mauris torquent eros taciti<br>
    Conubia curae vel himenaeos dictumst sed at</p>
  </blockquote>