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

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

    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 use print statements like you normally would, and don't open the file at all in your script. When you go to run the file, instead of

    ./script.py
    

    to run the file, use

    ./script.py > 
    

    where you replace 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 command

    chmod a+x script.py (make the script executable for all users)

提交回复
热议问题