右移运算符在 python print 语句中如何工作?

发布于 2024-09-06 07:01:18 字数 238 浏览 2 评论 0原文

我见过有人将“print”与“>>”一起使用将内容写入文件:

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

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

它是如何工作的?我什么时候应该使用它而不是仅仅使用“write”方法?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤城病女 2024-09-13 07:01:18

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

print 也有扩展形式,
由第二部分定义
语法如上所述。这个表格是
有时也称为“打印
雪佛龙。”在这种形式中,第一个
>> 之后的表达式必须评估
到“类似文件”的对象,特别是
具有 write() 方法的对象
如上所述。有了这个扩展
形式,后续表达式为
打印到此文件对象。如果
第一个表达式的计算结果为 None,
然后 sys.stdout 用作文件
用于输出。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文