【发布时间】:2015-04-25 03:09:55
【问题描述】:
我在 macbook 上使用终端将数据打印到打开的文件中:
>>> out=open("test_output.txt","w")
>>> print("hello",file=out)
File "<stdin>", line 1
print("hello",file=out)
^
SyntaxError: invalid syntax
为什么会有 SyntaxError 以及如何修复它?无论如何,相同的脚本在 IDLE 中运行良好。
PS:
它是 Python 2.7,我实际上已经安装了 Python 3.5,但是 NetworkX 和 Matplotlib 的包都自动安装到 Python 2.7 的库中,所以这是我在进行社交网络分析时使用的平台。
【问题讨论】:
-
这是 python 2 还是 3?
-
您实际上在尝试什么 print ?您是否尝试打印文件对象?
-
print()函数是 Python 3 的一个特性;如果文件以from __future__ import print_function开头,它也可以在 Python 2.6+ 中使用(通常推荐) -
@Antti - 次要澄清:您可以使用至少可以追溯到 Python 2.5 的
print()语法,但它只更改为 act 就像 3 中的一个函数,以及从 2.6 开始的__future__模块。就像你说的那样。 -
这是 python 2.7,感谢 Antti,它可以工作了!!