How to redirect 'print' output to a file using python?

后端 未结 11 1062
既然无缘
既然无缘 2020-11-22 17:05

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

11条回答
  •  忘了有多久
    2020-11-22 17:23

    You can redirect print with the >> operator.

    f = open(filename,'w')
    print >>f, 'whatever'     # Python 2.x
    print('whatever', file=f) # Python 3.x
    

    In most cases, you're better off just writing to the file normally.

    f.write('whatever')
    

    or, if you have several items you want to write with spaces between, like print:

    f.write(' '.join(('whatever', str(var2), 'etc')))
    

提交回复
热议问题