print(f) for files .. and is print % going away?

Duncan Booth duncan.booth at invalid.invalid
Thu Apr 30 07:31:36 EDT 2009


Esmail <ebonak at hotmail.com> wrote:

> Hello all,
> 
> I use the print method with % for formatting my output to
> the console since I am quite familiar with printf from my
> C days, and I like it quite well.
> 
> I am wondering if there is a way to use print to write
> formatted output to files?

Run python interactively and then enter help('print'), you'll get a long 
description of what print does the last paragraph of which I've 
reproduced here (but I've trimmed some of the output from the middle).

>>> help('print')
The ``print`` statement
***********************

   print_stmt ::= "print" ([expression ("," expression)* [","]]
                  | ">>" expression [("," expression)+ [","]])

...
``print`` also has an extended form, defined by the second portion of
the syntax described above. This form is sometimes referred to as
"``print`` chevron." In this form, the first expression after the
``>>`` must evaluate to a "file-like" object, specifically an object
that has a ``write()`` method as described above.  With this extended
form, the subsequent expressions are printed to this file object.  If
the first expression evaluates to ``None``, then ``sys.stdout`` is
used as the file for output.


> Also, it seems like I read that formatting with print is
> going away eventually and we should start using something
> else? Is that true and if so, what?

With python2.6 and later you can use the print function instead (but on 
python 2.x you have to enable it with an import):

>>> from __future__ import print_function
>>> help(print)
Help on built-in function print in module __builtin__:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current 
sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list