title: How to redirect 'print' output to a file?
body: <p>I want to redirect the print to a .txt file using Python. I have a <code>for</code> loop, which will <code>print</code> the output for each of my .bam file while I want to redirect <strong>all</strong> output to one file. So I tried to put:</p>
  <pre><code>f = open('output.txt','w')
  sys.stdout = f
  </code></pre>
  <p>at the beginning of my script. However I get nothing in the .txt file.
  My script is:</p>
  <pre><code>#!/usr/bin/python
  
  import os,sys
  import subprocess
  import glob
  from os import path
  
  f = open('output.txt','w')
  sys.stdout = f
  
  path= '/home/xxx/nearline/bamfiles'
  bamfiles = glob.glob(path + '/*.bam')
  
  for bamfile in bamfiles:
      filename = bamfile.split('/')[-1]
      print 'Filename:', filename
      samtoolsin = subprocess.Popen([&quot;/share/bin/samtools/samtools&quot;,&quot;view&quot;,bamfile],
                                    stdout=subprocess.PIPE,bufsize=1)
      linelist= samtoolsin.stdout.readlines()
      print 'Readlines finished!'
  </code></pre>
  <p>So what's the problem? Any other way besides this <code>sys.stdout</code>?</p>
  <p>I need my result look like:</p>
  <pre class="lang-none prettyprint-override"><code>Filename: ERR001268.bam
  Readlines finished!
  Mean: 233
  SD: 10
  Interval is: (213, 252)
  </code></pre>