How does Python simply redirect the printout to a TXT file and create a new line for each redirection (python2, python3 compatible)

If you are using Python 2.5 or earlier, please open the file and use the file object in the redirection:

log = open("c:\\goat.txt", "w") print >>log, "test"

If you use Python 2.6 or 2.7, you can use print as a function:

from __future__ import print_function
log = open("c:\\goat.txt", "w") print("test", file = log)

If you use Python3.0 or later, you can omit future imports.

If you want to redirect print statements globally, you can set sys.stdout:

import sys
sys.stdout = open("c:\\goat.txt", "w") print ("test sys.stdout")

Guess you like

Origin www.cnblogs.com/qiumingcheng/p/12686656.html