title: Read and overwrite a file in Python
body: <p>Currently I'm using this:</p>
  
  <pre><code>f = open(filename, 'r+')
  text = f.read()
  text = re.sub('foobar', 'bar', text)
  f.seek(0)
  f.write(text)
  f.close()
  </code></pre>
  
  <p>But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.</p>