connect file object to standard output?

Scott David Daniels scott.daniels at
Mon May 8 22:24:21 CEST 2006

beliavsky at wrote:
> .... I think there is a way to connect standard output to a
> file, but I'd prefer not to do that, since I want to use plain print
> statements to warn about errors in the function and have their output
> appear on the screen. Thanks.
> def write_data(data,out_file=""):
>     if (out_file != ""):
>         fp = open(out_file,"w")
>     else:
>         fp = # how to connect standard output to fp?
           fp = None
>     print >>fp, data
>     # more print>>fp statements follow

If you are only using "print >>x"-style statements, simply
set fp to None (which means "write on stdout").  That makes it
easier to only close the file you opened later., say by ending
the routine above with:

       if fp is not None:

--Scott David Daniels
scott.daniels at

More information about the Python-list mailing list