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

后端 未结 11 1154
既然无缘
既然无缘 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:28

    Python 2 or Python 3 API reference:

    print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

    The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

    Since file object normally contains write() method, all you need to do is to pass a file object into its argument.

    Write/Overwrite to File

    with open('file.txt', 'w') as f:
        print('hello world', file=f)
    

    Write/Append to File

    with open('file.txt', 'a') as f:
        print('hello world', file=f)
    

提交回复
热议问题