Using print instead of file.write(str)

Jon Clements joncle at
Thu Jun 1 23:33:21 CEST 2006

Didn't know of the >> syntax:  lovely to know about it Bruno - thank

To the OP - I find the print statement useful for something like:
print 'this','is','a','test'
>>> 'this is a test'
(with implicit newline and implicit spacing between parameters)

If you want more control (more flexibility, perhaps?) over the
formatting of the output: be it spacing between parameters or newline
control, use the methods Bruno describes below.

I'm not sure if you can suppress the spacing between elements (would
love to be corrected though); to stop the implicit newline use
something like
print 'testing',
>>> 'testing'
(but - with the leading comma, the newline is suppressed)

I personally find that print is convenient for sentences (or writing

Thought it worth pointing this out in case, like some I know, you come
across a cropper with certain output streams.

All the best,


Bruno Desthuilliers wrote:
> A.M a écrit :
> > Hi,
> >
> >
> > I found print much more flexible that write method. Can I use print instead
> > of file.write method?
> >
> f = open("/path/to/file")
> print >> f, "this is my %s message" % "first"
> f.close()
> To print to stderr:
> import sys
> print >> sys.stderr, "oops"
> FWIW, you and use string formating anywhere, not only in print statements:
> s = "some %s and % formating" % ("nice", "cool")
> print s
> You can also use "dict formating":
> names = {"other": "A.M.", "me" : "bruno"}
> s = "hello %(other)s, my name is %(me)s" % names

More information about the Python-list mailing list