title: Replace Multiple Lines in a File using Python
body: <p>I have a script that reads in values from one file and uses them to update fields in another file. It works great if I'm only doing one update, but if I add more (commented line) it breaks.</p>
  <pre class="lang-py prettyprint-override"><code>import re
  
  def update_template():
      with open(&quot;dest.txt&quot;, &quot;r&quot;) as template:
          lines = template.readlines()
      with open(&quot;dest.txt&quot;, &quot;w&quot;) as template:
          for line in lines:
              template.write(re.sub(field_one, one, line))
              template.write(re.sub(field_two, two, line))  # &lt;-- breaks here
  
  with open('source.txt') as source:
      for line in source:
          one = &quot;value1&quot;
          two = &quot;value2&quot;
          field_one = &quot;replace1&quot;
          field_two = &quot;replace2&quot;
          update_template();
  </code></pre>
  <p>Calling the function for each update works, but I have a lot of data so I'd rather not do that. Any ideas?</p>
  <p>Edit: If I have the following in <code>dest.txt</code>:</p>
  <pre class="lang-none prettyprint-override"><code>replace1
  replace2
  </code></pre>
  <p>Post-run I end up with:</p>
  <pre class="lang-none prettyprint-override"><code>value1
  value1
  value1
  replace1
  replace2
  value2
  value2
  value2
  </code></pre>
  <p>There should only be 'values' in there...</p>