print "hello", >> file

Alex Martelli aleax at aleax.it
Tue Feb 25 11:27:27 CET 2003


Yar3k wrote:

> On Tue, 25 Feb 2003 08:57:20 GMT, Alex Martelli <aleax at aleax.it>
> wrote:
> 
>>Hilbert wrote:
>>
>>> Hello,
>>> 
>>> Why does the following result in an error?
>>> 
>>> f = file("welcome.txt","w")
>>> print "hello", >> f
>>
>>Because the "print>>BAH" syntax is all wacko.  You
>>need to code:
>>    print >> f, "hello"
> 
> why not f.write("hello") ?

More generally, the equivalent of:

   print >> BAH, whatever

is

   BAH.write( str(whatever) + '\n' )

It's a bit subtler for the trailing-comma case:

   print >> BAH, whatever,

you can ALMOST simulate it with a trailing space:

   BAH.write( str(whatever) + ' ' )

however, this will leave a trailing space at the
end of the line if the very next thing written to
BAH is a newline; the print statement avoids this
subtle and generally undesired effect.


Alex





More information about the Python-list mailing list