【问题标题】:Python 2.7: Print to FilePython 2.7:打印到文件
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 您需要添加 '\n' 以使其等效于打印。
【解决方案2】:

print(args, file=f1) 是 python 3.x 语法。 对于 python 2.x,请使用 print &gt;&gt; f1, args。

【讨论】:

  • 我想你也应该提到from __future__ import print_function。然后你可以在 Python 2 和 3 中使用清晰的符号。
  • @moose,Gandaro 的回答已经很出色了,包括我的回答和你的笔记。
  • 我用你的 python3 语法得到AttributeError: 'str' object has no attribute 'write'
  • @Suncatcher,您可能正在尝试将包含文件名的字符串传递为 f1 而不是实际的文件对象。您需要先打开文件进行写入:f1 = open('path_to_your_file', 'w')
  • 是的,我认为应该是文件名,而不是文件对象。
【解决方案3】:

如果要在 Python 2 中使用 print 函数,则必须从 __future__ 导入:

from __future__ import print_function

但你也可以不使用该功能也有同样的效果:

print >>f1, 'This is a test'

【讨论】:

    【解决方案4】:

    在 Python 3.0+ 中,print 是一个函数,您可以使用 print(...) 调用它。在早期版本中,print 是一个声明,您可以使用 print ... 来创建。

    要在 Python 3.0 之前的版本中打印到文件,您可以:

    print >> f, 'what ever %d', i
    

    &gt;&gt; 运算符将打印定向到文件f。

    【讨论】:

    • 我想将整个数组打印到文件中。如果我使用您的代码,则只打印数组的头部和尾部,就像终端的输出一样。如何将所有数组行打印到文件中?
    • @Sigur "喜欢终端的输出" 抱歉,错误在别处。你没有告诉 Python 打印整个内容,这就是为什么它不是。
    【解决方案5】:

    您可以在不更改任何代码的情况下将打印语句导出到文件。只需打开一个终端窗口并以这种方式运行您的代码:

    python yourcode.py >> log.txt
    

    【讨论】:

      【解决方案6】:

      这会将您的“打印”输出重定向到文件:

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

      【讨论】:

      • 是猴子补丁吗?
      猜你喜欢
      • 2012-07-25
      • 1970-01-01
      • 2013-03-29
      • 2023-03-06
      • 2018-11-01
      • 2016-08-21
      • 2011-12-14
      • 1970-01-01
      • 2014-05-27
      相关资源
      最近更新 更多