I want to redirect the print to a .txt file using python. I have a 'for' loop, which will 'print' the output for each of my .bam file while I want to redirect ALL these output to one file. So I tried to put
f = open('output.txt','w'); sys.stdout = f
at the beginning of my script. However I get nothing in the .txt file. My script is:
#!/usr/bin/python
import os,sys
import subprocess
import glob
from os import path
f = open('output.txt','w')
sys.stdout = f
path= '/home/xug/nearline/bamfiles'
bamfiles = glob.glob(path + '/*.bam')
for bamfile in bamfiles:
filename = bamfile.split('/')[-1]
print 'Filename:', filename
samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile],
stdout=subprocess.PIPE,bufsize=1)
linelist= samtoolsin.stdout.readlines()
print 'Readlines finished!'
........print....
........print....
So what's the problem? Any other way besides this sys.stdout?
I need my result look like:
Filename: ERR001268.bam
Readlines finished!
Mean: 233
SD: 10
Interval is: (213, 252)
The easiest solution isn't through python; its through the shell. From the first line of your file (
#!/usr/bin/python
) I'm guessing you're on a UNIX system. Just useprint
statements like you normally would, and don't open the file at all in your script. When you go to run the file, instead ofto run the file, use
where you replace
<filename>
with the name of the file you want the output to go in to. The>
token tells (most) shells to set stdout to the file described by the following token.One important thing that needs to be mentioned here is that "script.py" needs to be made executable for
./script.py
to run.So before running
./script.py
,execute this commandchmod a+x script.py
(make the script executable for all users)You can redirect print with the
>>
operator.In most cases, you're better off just writing to the file normally.
or, if you have several items you want to write with spaces between, like
print
:if ur using linux i suggest u to use
tee
command the implementation goes like this pythonpython_file.py |tee any_file_name.txt
if u dont want to change anything in the code ,i think this might be the best possible solution ,u can also implement logger but u need do some changes in the code.Changing the value of sys.stdout does change the destination of all calls to print. If you use an alternative way to change the destination of print, you will get the same result.
Your bug is somewhere else: