Python 2.7:打印至文件

100
为什么尝试直接打印到文件而不是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.

那么正确的语法是什么,可以更改标准流的打印输出吗?

我知道有不同的,也许更好的方法来写入文件,但我真的不明白为什么这应该是一个语法错误...

欢迎提供一个好的解释!


4
你确定吗?print()是Python 3.x内置函数,而print是Python < 3.x的运算符。该帖子显示为2.7.2+ - khachik
2
你是否使用了 from __future__ import print_function ?在 Python < 3 中,print 是一个语句。 - Ari
1
不!我没有。当然,你是对的。问题解决了。该死!因此,在 help(_builtins_) 中记录的 print 是未来(3.x)版本的 print,其具有不同的语法。非常感谢你和你,kachik。 - alex
2
在我看来,help(__builtins__) 显示所有内容是一个错误。 - Wooble
4
虽然进一步调查后发现 Python 2.7.2 实际上 内置的打印函数,但通常情况下你无法轻松访问它(不过 __builtins__.__dict__['print'](value, file=f1) 可以正常工作)。 - Wooble
6个回答

140

如果您想在Python 2中使用print函数,则需要从__future__导入:

from __future__ import print_function

但是您也可以不使用该函数来实现相同的效果:

print >>f1, 'This is a test'

使用 print >> 的缺点是它在 Python 3 中无法工作。导入是实现跨版本兼容代码的最佳方式。 - Toby Speight

73

print是Python 2.X中的关键字。您应该使用以下内容:

f1=open('./testfile', 'w+')
f1.write('This is a test')
f1.close()

3
你需要添加 '\n' 以使其与 print 等效。 - jlh

44

print(args, file=f1) 是Python 3.x的语法。 对于Python 2.x,请使用print >> f1, args


4
我认为你还应该提到 from __future__ import print_function。这样你就可以在 Python 2 和 3 中都使用清晰的符号表示法。 - Martin Thoma
@moose,已经有一个非常好的Gandaro的答案了,其中包括了我的回答和你的注释。 - citxx
2
我使用你的Python3语法出现了AttributeError: 'str' object has no attribute 'write'错误。 - Suncatcher
6
@Suncatcher,你可能试图将包含文件名的字符串作为f1传递,而不是实际的文件对象。你需要首先打开文件进行写操作:f1 = open('path_to_your_file', 'w') - citxx
是的,我认为应该是文件名而不是文件对象。 - Suncatcher

15

这将把您的“print”输出重定向到一个文件中:

import sys
sys.stdout = open("file.txt", "w+")
print "this line will redirect to file.txt"

这是猴子补丁吗? - Sarath Sadasivan Pillai
1
那会覆盖所有未来的写入stdout,这是一个问题副作用。 - Toby Speight

13

您可以将打印语句导出到文件中,而无需更改任何代码。只需打开终端窗口并以以下方式运行您的代码:

python yourcode.py >> log.txt

这会重定向 所有 输出,而不仅仅是单个打印语句! - Toby Speight

6
在Python 3.0及以上版本中,print是一个函数,您需要使用print(...)进行调用。在早期版本中,print是一个语句,您需要使用print ...进行创建。
在Python 3.0之前的版本中,要将内容打印到文件中,您需要执行以下操作:
print >> f, 'what ever %d', i
< p > >> 操作符将打印内容定向到文件f


我想将整个数组打印到文件中。如果我使用您的代码,只有数组的头部和尾部被打印出来,就像终端输出一样。如何将所有数组行都打印到文件中? - Sigur
2
@Sigur “像终端输出一样” 抱歉,但问题不在这里。你没有告诉 Python 打印整个内容,这就是为什么它没有输出全部内容的原因。 - wizzwizz4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接