【发布时间】:2012-03-08 03:08:45
【问题描述】:
为什么尝试直接打印到文件而不是 sys.stdout 会产生以下语法错误:
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
来自 help(__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 2.7.2+。 -
你
from __future__ import print_function了吗?在 Python -
不!我没有。你当然是对的。这样就解决了问题。该死!所以 help(_builtins_) 中记录的 print 是 print 的未来(3.x)版本,它具有不同的语法。非常感谢你和你,kachik
-
IMO,
help(__builtins__)显示这根本是一个错误。 -
...虽然,进一步调查,python 2.7.2 确实 有一个内置的打印功能,你只是不能正常访问它(
__builtins__.__dict__['print'](value, file=f1)确实不过工作)。
标签: python file python-2.7