tags:

views:

60

answers:

2

I've seen someone using "print" with ">>" to write stuffs into a file:

In [7]: with open('text', 'w') as f:
   ...:     print >> f, "Hello, world!"
   ...:

In [8]: !type text
Hello, world!

How does it work? When should I use this instead of just using the "write" method?

+3  A: 

From http://docs.python.org/reference/simple_stmts.html#print

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.

Ed
Perhaps worth noting that this extended form no longer exists in Python 3, so new code should probably avoid it.
Mark Dickinson
A: 

Good question as I've never seen that before! From my stand point if you are going to write to a file wise the functions supplied for that. Maybe someone else has a different opinion but I'm not sure what this form offers up except possibly making it easier to change the file being written to.

Dave

David Frantz