>\" to write stuffs into a file: In [7]: with open(\'text\', \'w\') as f:" />
开发者

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

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开发者_JAVA百科 I use this instead of just using the "write" method?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜