[Tutor] output formatting

Lie Ryan lie.1296 at gmail.com
Mon Apr 27 09:09:14 CEST 2009

Matt Domeier wrote:
> Hi Wayne,
> Yes, that should work perfectly, but it is in writing files that I'm 
> having the problem. I'm still very new to python, so I only know to use 
> something like filename.write(str(listname)) to write my list to a file..
> Is there a straightforward method of combining the ease of the print 
> function setup that you suggested with write? 

> Or could I somehow use the 
> print function itself to write to the file (rather than just output to 
> my shell/prompt)?

First note, print is a statement in python2.x and a function in python3.x.

In both case it is possible to redirect print's output to another file. 

print >> f, "Hello World"

print("Hello World", file=f)

also for both versions:

import sys
sys.stdout = f
print("Hello World")
sys.stdout = sys.__stdout__ # return to normal

The universal stdout redirection (3rd method) was discouraged because it 
could mess up things if there are two or more routines that tries to 
override sys.stdout or in multithreading situation (it is there mainly 
for hackish quick and dirty scripts). The python2.x's redirection method 
looks ugly (for me). The python3.x's syntax is better, but is a bit verbose.

In any case, it is usually more recommended to use f.write() or 

More information about the Tutor mailing list