Python 如何将打印输出重定向到 TXT 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4110891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:18:16  来源:igfitidea点击:

How to redirect the output of print to a TXT file

pythonprintingredirect

提问by surfdork

I have searched Google, Stack Overflow and my Python users guide and have not found a simple, workable answer for the question.

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

I created a file c:\goat.txt on a Windows 7 x64 machine and am attempting to print "test" to the file. I have tried the following based on examples provided on StackOverflow:

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

At this point I don't want to use the log module since I don't understand from the documentation of to create a simple log based upon a binary condition. Print is simple however how to redirect the output is not obvious.

在这一点上,我不想使用 log 模块,因为我从文档中不明白基于二进制条件创建一个简单的日志。打印很简单,但是如何重定向输出并不明显。

A simple, clear example that I can enter into my interperter is the most helpful.

一个我可以输入到我的互操作者中的简单、清晰的例子是最有帮助的。

Also, any suggestions for informational sites are appreciated (NOT pydocs).

此外,对信息站点的任何建议表示赞赏(不是 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

回答by Eli Courtwright

If you're on Python 2.5 or earlier, open the file and then use the file object in your redirection:

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

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

If you're on Python 2.6 or 2.7, you can use print as a function:

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

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

If you're on Python 3.0 or later, then you can omit the future import.

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

If you want to globally redirect your print statements, you can set sys.stdout:

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

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

回答by kolobos

To redirect output for allprints, you can do this:

要重定向所有打印的输出,您可以执行以下操作:

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

回答by user3731311

Redirect sys.stdout to an open file handle and then all printed output goes to a file:

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

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

回答by Tristan Tao

A slightly hackier way (that is different than the answers above, which are all valid) would be to just direct the output into a file via console.

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

So imagine you had main.py

所以想象你有 main.py

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

You can do

你可以做

python main.py >> text.log

and then text.log will get all of the output.

然后 text.log 将获得所有输出。

This is handy if you already have a bunch of print statements and don't want to individually change them to print to a specific file. Just do it at the upper level and direct all prints to a file (only drawback is that you can only print to a single destination).

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

回答by Flippym

Usinge the fileargument in the printfunction, you can have different files per print:

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

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

回答by z33k

Building on previous answers, I think it's a perfect use case for doing it (simple) context manager style:

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

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__

and then:

进而:

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

Also it would be really easy to add some functionality to StdoutRedirectionclass (e.g. a method that lets you change the path)

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

回答by clint

simple in python 3.6

python 3.6中的简单

o = open('outfile','w')

print('hello world', file=o)

o.close()

I was looking for something like I did in Perl

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

my $printname = "outfile"

open($ph, '>', $printname)
    or die "Could not open file '$printname' $!";

print $ph "hello world\n";

回答by Sijin John

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)

Please add encoding="utf-8"so as to avoid the error of " 'charmap' codec can't encode characters in position 12-32: character maps to "

请添加encoding="utf-8"以避免出现“'charmap' codec can't encode characters in position 12-32: character maps to”的错误