Next: Other Methods
Up: File Objects
Previous: Methods for Writing
  Contents
Since the write method does not append a newline character to each line
which it writes
to a file, it is often inconvenient to convert a program which uses the print
statement (which does append newlines) to one which will direct its output to a file.
To make this easier, an
extended form of the print statement was introduced in version 2 of python.
To use this form, it is still necessary to create a file object which is opened for
writing, but instead of invoking the write method, the file object can
be specified on the print statement, preceded by two right brackets
(»), and followed by a comma. Thus, if we had a program which was designed
to print to standard output with a statment like
print msg;
we could modify it to write to a file called ``output.file'' by first
creating a file object suitable for writing:
try:
outfile = open('output.file','w')
except IOError:
print 'output.file could not be opened'
sys.exit(1)
and then using the following print statement:
print >> outfile, msg;
Phil Spector
2003-11-12