How to redirect the output of print to a TXT file How to redirect the output of print to a TXT file python python

How to redirect the output of print to a TXT file


If you're on Python 2.5 or earlier, open the file and then use the file object in your redirection:

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

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

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

If you're on Python 3.0 or later, then you can omit the future import.

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

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


To redirect output for all prints, you can do this:

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


A slightly hackier way (that is different than the answers above, which are all valid) would be to just direct the output into a file via console.

So imagine you had main.py

if True:    print "hello world"else:    print "goodbye world"

You can do

python main.py >> text.log

and then text.log will get all of the output.

This is handy if you already have a bunch of print statements and don't want to individually change them to print to a specific file. Just do it at the upper level and direct all prints to a file (only drawback is that you can only print to a single destination).