title: How do I regex sub (re.sub) for multiple lines in Python?
body: <p>I am trying to replace two separate lines in a file using regular expressions. </p>
  
  <p>Each 'with open("release.spec", "w")' statement works if used on it's own, but if used together, It only updates the second one, and not the first. </p>
  
  <pre><code>import re
  import time
  
  ver = time.strftime('%Y.%m')
  ts = time.strftime('%a %b %d %Y')
  
  with open("release.spec", "r") as spec_file:
      lines = spec_file.readlines()
  
  with open("release.spec", "w") as spec_file:
      for line in lines:
          spec_file.write(re.sub(r'^Version.*$', 'Version\t\t ' + ver, line))
  
  with open("release.spec", "w") as spec_file:        
      for line in lines:   
          spec_file.write(re.sub(r'^%changelog', '%changelog\n' + \
              '* ' + ts + ' Linux Admin &lt;root@localhost&gt;\n' + \
              '- Release cycle ' + ver \
              , line))
  </code></pre>
  
  <p>Why does it not substitute on both lines? What would an easier method be to write both statements, preferable in one open write statement? If I try something like the following, it duplicates each line.</p>
  
  <pre><code>with open("release.spec", "w") as spec_file:
      for line in lines:
          spec_file.write(re.sub(r'^Version.*$', 'Version\t\t ' + ver, line))
          spec_file.write(re.sub(r'^%changelog', '%changelog\n' + \
              '* ' + ts + ' Linux Admin &lt;root@localhost&gt;\n' + \
              '- Release cycle ' + ver \
              , line))
  </code></pre>