title: Using Linux redirect to overwrite file from Python script
body: <p>I have a simple python script that just takes in a filename, and spits out a modified version of that file. I would like to redirect stdout (using '>' from the command line) so that I can use my script to overwrite a file with my modifications, e.g. <code>python myScript.py test.txt &gt; test.txt</code></p>
  
  <p>When I do this, the resulting test.txt does not contain any text from the original test.txt - just the additions made by myScript.py. However, if I don't redirect stdout, then the modifications come out correctly.</p>
  
  <p>To be more specific, here's an example:</p>
  
  <hr>
  
  <p>myScript.py:</p>
  
  <pre><code>#!/usr/bin/python
  import sys
  
  fileName = sys.argv[1]
  sys.stderr.write('opening ' + fileName + '\n')
  
  fileHandle = file(fileName)
  currFile = fileHandle.read()
  fileHandle.close()
  
  sys.stdout.write('MODIFYING\n\n' + currFile + '\n\nMODIFIED!\n')
  </code></pre>
  
  <hr>
  
  <p>test.txt</p>
  
  <pre><code>Hello World
  </code></pre>
  
  <hr>
  
  <p>Result of <code>python myScript.py test.txt &gt; test.txt</code>:</p>
  
  <pre><code>MODIFYING
  
  
  
  MODIFIED!
  </code></pre>