How does the right-shift operator work in a python print statement?

前端 未结 1 351
故里飘歌
故里飘歌 2020-12-11 01: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, w         


        
1条回答
  •  再見小時候
    2020-12-11 01:27

    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.

    0 讨论(0)
提交回复
热议问题