redirecting python's "print" statements to a file

7 October, 2005 - 12:05
Categories:

Something I find annoying about writing a program/script that writes to text files is that you explicitly have to write the linefeeds (things like "\n", "\r", "\r\n" or std::endl). I remember Pascal having something like a writeln() function, which was very handy when I spend my time programming in TurboPascal, but it's no real incentive at all to return to the "begin...end" mess of Pascal. Apparently java has a writeln function too.

In Python you have the print statement, which also silently appends a linefeed (unless you end the statement with a comma). The default behaviour of print is to write to the standard output, but you can redirect this to files or other writable objects (technically all objects that have a write method). That way you can use short, simple and clear print statements instead of those cluttered object.write( "wello horld" + "\n") constructs.

The first technique is based on redirecting sys.stdout by assigning a writable object (such as a file object) to it. The print statements that follow will write to that object, instead of the default standard output. The drawback is that you should remember to reset sys.stdout to sys.__stdout__ if you want your default standard output back.

The second technique came to my attention when I reread Learning Python for the second time. It involves redirecting the print statement directly as follows:

print >>output, "wello horld"

in which output is a writable object.

As an illustration, consider the following script:

#!/usr/bin/python
import sys
 
# a simple class with a write method
class WritableObject:
    def __init__(self):
        self.content = []
    def write(self, string):
        self.content.append(string)
 
# example with redirection of sys.stdout
foo = WritableObject()                   # a writable object
sys.stdout = foo                         # redirection
print "one, two, three, four"            # some writing
print "little hat"
print "little hat"
sys.stdout = sys.__stdout__              # remember to reset sys.stdout!
print "foo's content:", foo.content                # show the result of the writing
 
# example with redirection of the print statement
bar = WritableObject()                   # another writable object
print >>bar, "one, two, three, four"     # some (redirected) writing
print >>bar, "little hat made of paper"
print "bar's content:", bar.content                # the result

the output of this script is

foo's content: ['one, two, three, four', '\n', 'little hat', '\n', 'little hat', '\n']
bar's content: ['one, two, three, four', '\n', 'little hat made of paper', '\n']

In a more real life situation (for example with file objects to write to), this can be very handy and keeps you code cleaner and more human readable.

14 September, 2011 - 16:49

Thanks for the post.

Anonymous (not verified)

Thanks for the post.

25 June, 2011 - 02:35

'int' object has no attribute 'write'

Anonymous (not verified)

Trying to redirect stdout, I'm getting:

File "./scanartwork", line 99, in
print "-------------------"
AttributeError: 'int' object has no attribute 'write'

28 May, 2010 - 12:33

nice

CrystY (not verified)

Nice to know this. I used them both to do a duplicate/redirect

6 January, 2010 - 18:41

Thanks for this post, it was

Harun (not verified)

Thanks for this post, it was very helpful.

15 April, 2009 - 16:11

Thank god for the >> thingy.

Anonymous (not verified)

Thank god for the >> thingy. It seems the python documentation never tells you what youre looking for :)

29 May, 2007 - 16:35

Thanks!

Anonymous

This helped me print a long table list from stdout to a text file:

>>> import sys
>>> sys.stdout = open('c:/log3.txt','w')  
>>> print str(odbc.print_resultset(c))  
>>> sys.stdout=sys.__stdout__   
6 January, 2009 - 23:41

Simple and usefull!

Anonymous (not verified)

thanks for this! most appreciated.....

4 May, 2006 - 13:39

RE: redirecting python's "print" statements to a file

Shreyas (not verified)

I'm using python 2.4 and the code written above fails.

Traceback (most recent call last):
  File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\intpyapp.py", line 341, in OnFileRun
    scriptutils.RunScript(None, None, showDlg)
  File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 348, in RunScript
    sys.stdout.flush()
IOError: [Errno 9] Bad file descriptor
win32ui: Error in Command Message handler for command ID 36864, Code 0
23 June, 2010 - 10:45

pythonw and stdout

Vaida Bogdan (not verified)

@Shreyas I had the same problem, check this link: http://bugs.python.org/issue973507

Post new comment

The content of this field is kept private and will not be shown publicly.
  • No HTML tags allowed
  • Lines and paragraphs break automatically.

More information about formatting options