title: Search and replace a line in a file in Python
body: <p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p>
  
  <p>What is the best way to do this, within the following code?</p>
  
  <pre><code>f = open(file)
  for line in f:
      if line.contains('foo'):
          newline = line.replace('foo', 'bar')
          # how to write this newline back to the file
  </code></pre>