[Tutor] Writing to output file

Martijn Faassen M.Faassen@vet.uu.nl
Thu, 25 Mar 1999 21:56:22 +0100


Hiya,

You can write strings to a textfile, of course, and first translate
other types to strings, using str() or using the % operator. "%s" %
a_value, for instance.

Another way is to redirect sys.stdout to a file object. That makes all
your print statements print to the file instead of to the console:

# import sys to get at stdout (standard output)
import sys

# open a file for writing
f = open("myfile.txt", "w")
# okay, our standard output is now that file
sys.stdout = f

# this prints to the file
print "Foo", 6, "bar"

I hope this helps,

Regards,

Martijn