How to redirect the output of print to a TXT file

surfdork picture surfdork · Nov 6, 2010 · Viewed 164.9k times · Source

I have searched Google, Stack Overflow and my Python users guide and have not found a simple, workable answer for the question.

I created a file c:\goat.txt on a Windows 7 x64 machine and am attempting to print "test" to the file. I have tried the following based on examples provided on StackOverflow:

At this point I don't want to use the log module since I don't understand from the documentation of to create a simple log based upon a binary condition. Print is simple however how to redirect the output is not obvious.

A simple, clear example that I can enter into my interperter is the most helpful.

Also, any suggestions for informational sites are appreciated (NOT pydocs).

import sys
print('test', file=open('C:\\goat.txt', 'w')) #fails
print(arg, file=open('fname', 'w')) # above based upon this
print>>destination, arg

print>> C:\\goat.txt, "test" # Fails based upon the above

Answer

Eli Courtwright picture Eli Courtwright · Nov 6, 2010

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_function
log = 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 sys
sys.stdout = open("c:\\goat.txt", "w")
print ("test sys.stdout")