You can do it as shown in the other answers, but it gets kind of old specifying the output file in every statement. So I understand the urge to just redirect sys.stdout
. But yes, the way you propose doing it is not as elegant as it could be. Adding proper error handling will make it even uglier. Fortunately, you can create a handy context manager to address these issues:
import sys, contextlib
@contextlib.contextmanager
def writing(filename, mode="w"):
with open(filename, mode) as outfile:
prev_stdout, sys.stdout = sys.stdout, outfile
yield prev_stdout
sys.stdout = prev_stdout
Usage:
with writing("filename.txt"):
print "This is going to the file"
print "In fact everything inside the with block is going to the file"
print "This is going to the console."
Note that you can use the as
keyword to get the previous stdout
, so you can still print to the screen inside the with
block:
with writing("filename.txt") as stdout:
print "This is going to the file"
print >> stdout, "This is going to the screen"
print "This is going to the file again"