needed: :\codec:\python \python import sys temp sys stdout sys stdout open('log txt'' 'print('spam'print( sys stdout close(sys stdout temp print('back here'back here print(open('log txt'read()spam save for restoring later redirect prints to file prints go to filenot here flush output to disk restore original stream prints show up here again result of earlier prints as you can seethoughmanual saving and restoring of the original output stream like this involves quite bit of extra work because this crops up fairly oftena print extension is available to make it unnecessary in xthe file keyword allows single print call to send its text to the write method of file (or file-like object)without actually resetting sys stdout because the redirection is temporarynormal print calls keep printing to the original output stream in xa print statement that begins with >followed by an output file object (or other compatible objecthas the same effect for examplethe following again sends printed text to file named log txtlog open('log txt'' 'print(xyzfile=logprint(abc print to file-like object print to original stdout log open('log txt'' 'print >logxyz print abc print to file-like object print to original stdout these redirected forms of print are handy if you need to print to both files and the standard output stream in the same program if you use these formshoweverbe sure to give them file object (or an object that has the same write method as file object)not file' name string here is the technique in actionc:\codec:\python \python log open('log txt'' 'print( file=logprint( file=loglog close(print( for xprint >log for xprint in both and you may also be able to use the __stdout__ attribute in the sys modulewhich refers to the original value sys stdout had at program startup time you still need to restore sys stdout to sys __stdout__ to go back to this original stream valuethough see the sys module documentation for more details print operations