【问题标题】:How to redirect the output of print to a TXT file如何将打印输出重定向到 TXT 文件
【发布时间】:2011-05-05 21:12:32
【问题描述】:

我已经搜索了 Google、Stack Overflow 和我的 Python 用户指南,但没有找到一个简单、可行的问题答案。

我在 Windows 7 x64 机器上创建了一个文件 c:\goat.txt 并尝试将“test”打印到该文件。我根据 StackOverflow 上提供的示例尝试了以下方法:

此时我不想使用日志模块,因为我从文档中不了解如何根据二进制条件创建简单的日志。打印很简单,但是如何重定向输出并不明显。

一个简单明了的例子,我可以输入我的解释者是最有帮助的。

此外,感谢您对信息网站的任何建议(不是 pydocs)。

import sys
print('test', file=open('C:\\goat.txt', 'w')) #fails
print(arg, file=open('fname', 'w')) # above based upon this
print>>destination, arg

print>> C:\\goat.txt, "test" # Fails based upon the above

【问题讨论】:

  • 另外,你用的是什么教程? “搜索了几个小时而没有结果”应该替换为“做了几个小时的教程”。你有没有打开任何教程?如果有,是哪一个?

标签: python printing redirect


【解决方案1】:

如果您使用的是 Python 2.5 或更早版本,请打开文件,然后在重定向中使用文件对象:

log = open("c:\\goat.txt", "w")
print >>log, "test"

如果您使用的是 Python 2.6 或 2.7,则可以使用 print 作为函数:

from __future__ import print_function
log = open("c:\\goat.txt", "w")
print("test", file = log)

如果您使用的是 Python 3.0 或更高版本,则可以省略将来的导入。

如果你想全局重定向你的打印语句,你可以设置 sys.stdout:

import sys
sys.stdout = open("c:\\goat.txt", "w")
print ("test sys.stdout")

【讨论】:

  • 导入此打印功能会使我的其他打印语句出错。 print "Starting LfD..." ^ SyntaxError: invalid syntax
  • @BenBlumer:这是一个很好的观点;您应该只在您愿意将所有打印语句转换为函数调用的文件中进行打印函数的未来导入。
  • 要重置回标准输出,请使用代码:sys.stdout = sys.__stdout__
  • 实际上,在 3.0 或更高版本中,您可以将文件作为关键字 arg 提供:with open('myfile','w') as f: print("my example", file=f)
【解决方案2】:

要重定向所有打印的输出,您可以这样做:

import sys
with open('c:\\goat.txt', 'w') as f:
    sys.stdout = f
    print "test"

【讨论】:

  • 之后您可以使用以下命令将 set stdout 设置回原始状态:sys.stdout = sys.__stdout__
  • 最好重新分配sys.stdout 其默认值,如此处所述stackoverflow.com/a/7152903/1054978
【解决方案3】:

一种稍微复杂的方法(与上面的答案不同,它们都是有效的)是通过控制台将输出定向到文件中。

所以想象一下你有main.py

if True:
    print "hello world"
else:
    print "goodbye world"

你可以的

python main.py >> text.log

然后 text.log 会得到所有的输出。

如果您已经有一堆打印语句并且不想单独更改它们以打印到特定文件,这很方便。只需在上层执行此操作并将所有打印内容定向到一个文件(唯一的缺点是您只能打印到一个目标)。

【讨论】:

  • 因此,除此之外,我在 PyCharm 的运行配置中添加了一个“启动前”脚本,该脚本在 python 覆盖之前将 text.log/output.log 的内容复制到文件“concatenated_output.log”旧的 text.log/output.log。这样你就有了一个工作历史日志(日志包在我的情况下不起作用)。提示:确保在输出中的某处打印日期+时间
【解决方案4】:

基于以前的答案,我认为这是一个完美的用例(简单)上下文管理器样式:

import sys

class StdoutRedirection:
    """Standard output redirection context manager"""

    def __init__(self, path):
        self._path = path

    def __enter__(self):
        sys.stdout = open(self._path, mode="w")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = sys.__stdout__

然后:

with StdoutRedirection("path/to/file"):
    print("Hello world")

此外,向StdoutRedirection 类添加一些功能也很容易(例如,让您更改路径的方法)

【讨论】:

    【解决方案5】:

    在print 函数中使用file 参数,每次打印可以有不同的文件:

    print('Redirect output to file', file=open('/tmp/example.log', 'w'))
    

    【讨论】:

      【解决方案6】:

      python 3.6 中的简单

      o = open('outfile','w')
      
      print('hello world', file=o)
      
      o.close()
      

      我一直在寻找像我在 Perl 中所做的那样

      my $printname = "outfile"
      
      open($ph, '>', $printname)
          or die "Could not open file '$printname' $!";
      
      print $ph "hello world\n";
      

      【讨论】:

        【解决方案7】:
        from __future__ import print_function
        log = open("s_output.csv", "w",encoding="utf-8")
        for i in range(0,10):
           print('\nHeadline: '+l1[i], file = log)
        

        请添加encoding="utf-8"以避免出现“'charmap'编解码器无法编码位置12-32的字符:字符映射到”的错误

        【讨论】:

          【解决方案8】:

          将 sys.stdout 重定向到一个打开的文件句柄,然后所有打印的输出都转到一个文件:

          import sys
          filename  = open("outputfile",'w')
          sys.stdout = filename
          print "Anything printed will go to the output file"
          

          【讨论】:

          • 当我运行“sys.stdout = filename”时,程序冻结,不知道出了什么问题。
          • 也许标准输出必须分配给缓冲区的指针本身而不是引用。
          • 如果您以交互方式输入 python 解释器,请不要尝试重新分配 sys.stdout,因为您将不再看到解释器的任何输出。因为它使用标准输出。另外 - 不要锯掉你坐在的任何树枝。 :-)
          猜你喜欢
          • 2016-08-02
          • 1970-01-01
          • 2011-11-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-02
          • 1970-01-01
          • 2016-06-26
          相关资源
          最近更新 更多