为什么尝试直接打印到文件,而不是sys.stdout
产生以下语法错误:Python 2.7版:打印到文件
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1=open('./testfile', 'w+')
>>> print('This is a test', file=f1)
File "<stdin>", line 1
print('This is a test', file=f1)
^
SyntaxError: invalid syntax
从帮助(__ builtins__)我有以下信息:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
那么更改标准流打印写入的正确语法是什么?
我知道,有不同的也许更好的方法来写文件,但我真的不明白为什么这应该是一个语法错误...
一个很好的解释,将不胜感激!
你确定吗? 'print()'是python 3.x内置函数,而'print'是python <3.x运算符。这篇文章显示了'2.7.2 +'。 – khachik 2012-02-16 17:31:32
您是否从__future__导入print_function?在Python <3中,print是一个声明: – Ari 2012-02-16 17:32:23
不!我没有。你当然是对的。解决了这个问题。该死!因此,帮助(\ __ builtins__)中记录的打印是具有不同语法的打印版本(3.x)。非常感谢你,你也是,kachik – alex 2012-02-16 17:40:21