19

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?

Wang Dingwei
  • 4,661
  • 6
  • 32
  • 43

1 Answers1

16

From https://docs.python.org/2/reference/simple_stmts.html#the-print-statement

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.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
Ed.
  • 1,934
  • 15
  • 13
  • 7
    Perhaps worth noting that this extended form no longer exists in Python 3, so new code should probably avoid it. – Mark Dickinson Jun 20 '10 at 10:36
  • 5
    This isn't actually the `>>` operator in this case; the parser handles it specially as part of the `print` syntax. – abarnert May 10 '15 at 07:57