将打印输出定向到 Python 3 中的 .txt 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36571560/
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-19 18:02:35  来源:igfitidea点击:

Directing print output to a .txt file in Python 3

pythonpython-3.x

提问by Clone

Is there a way to save all of the print output to a txt file in python? Lets say I have the these two lines in my code and I want to save the print output to a file named output.txt.

有没有办法将所有打印输出保存到python中的txt文件?假设我的代码中有这两行,我想将打印输出保存到一个名为output.txt.

print ("Hello stackoverflow!")
print ("I have a question.")

I want the output.txtfile to to contain

我希望output.txt文件包含

Hello stackoverflow!
I have a question.

回答by Aaron Christiansen

Give printa filekeyword argument, where the value of the argument is a file stream. We can create a file stream using the openfunction:

给出print一个file关键字参数,其中参数的值是一个文件流。我们可以使用以下open函数创建文件流:

print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))

From the Python documentation about print:

从关于 的Python 文档中print

The fileargument must be an object with a write(string)method; if it is not present or None, sys.stdoutwill be used.

所述file参数必须是与对象write(string)方法; 如果它不存在或None,sys.stdout将被使用。

And the documentation for open:

文档open

Open fileand return a corresponding file object. If the file cannot be opened, an OSErroris raised.

打开file并返回一个对应的文件对象。如果无法打开文件,OSError则会引发an 。

The " a "as the second argument of openmeans "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead, use "w".

" a "作为第二个参数open是指“追加” -换句话说,文件的现有内容不会被覆盖。如果您希望文件被覆盖,请使用"w".



Opening a file with openmany times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print's fileoption. You must remember to close the file afterward!

open但是,多次打开文件对于性能来说并不理想。理想情况下,您应该将其打开一次并命名,然后将该变量传递给print'sfile选项。之后你一定要记得关闭文件!

f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()

There's also a syntactic shortcut for this, which is the withblock. This will close your file at the end of the block for you:

对此还有一个语法快捷方式,即with块。这将在块的末尾为您关闭您的文件:

with open("output.txt", "a") as f:
    print("Hello StackOverflow!", file=f)
    print("I have a question.", file=f)

回答by Roman Bronshtein

You can redirect stdout into a file "output.txt":

您可以将标准输出重定向到文件“output.txt”:

import sys
sys.stdout = open('output.txt','wt')
print ("Hello stackoverflow!")
print ("I have a question.")

回答by gies0r

Use the logging module

使用日志模块

def init_logging():
    rootLogger = logging.getLogger('my_logger')

    LOG_DIR = os.getcwd() + '/' + 'logs'
    if not os.path.exists(LOG_DIR):
        os.makedirs(LOG_DIR)
    fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
    rootLogger.addHandler(fileHandler)

    rootLogger.setLevel(logging.DEBUG)

    consoleHandler = logging.StreamHandler()
    rootLogger.addHandler(consoleHandler)

    return rootLogger

Get the logger:

获取记录器:

logger = init_logging()

And start logging/output(ing):

并开始记录/输出(ing):

logger.debug('Hi! :)')

回答by S3DEV

Another method without having to update your Python code at all, would be to redirect via the console.

另一种无需更新 Python 代码的方法是通过 console 重定向

Basically, have your Python script print()as usual, then call the script from the command line and use command line redirection. Like this:

基本上,print()像往常一样使用Python 脚本,然后从命令行调用脚本并使用命令行重定向。像这样:

$ python ./myscript.py > output.txt

Your output.txtfile will now contain all output from your Python script.

您的output.txt文件现在将包含 Python 脚本的所有输出。

回答by Chandra Shekhar

Suppose my input file is "input.txt" and output file is "output.txt":

假设我的输入文件是“input.txt”,输出文件是“output.txt”:

Let's consider the input file has details to read : 5 1 2 3 4 5

让我们考虑输入文件的详细信息: 5 1 2 3 4 5

==============================================================

================================================== ============

import sys

sys.stdin = open("input", "r")
sys.stdout = open("output", "w")

print("Reading from input File : ")
n = int(input())
print("Value of n is :", n)

arr = list(map(int, input().split()))
print(arr)

============================================================

================================================== ==========

So this will read from input file and output will be displayed in output file.

所以这将从输入文件中读取,输出将显示在输出文件中。

For more details please see : [https://www.geeksforgeeks.org/inputoutput-external-file-cc-java-python-competitive-programming/][1]

有关更多详细信息,请参阅:[ https://www.geeksforgeeks.org/inputoutput-external-file-cc-java-python-competitive-programming/][1]

回答by vic

Another Variation can be... Be sure to close the file afterwards

另一个变化可能是...之后一定要关闭文件

import sys
file = open('output.txt', 'a')
sys.stdout = file

print("Hello stackoverflow!") 
print("I have a question.")

file.close()

回答by Asiis Pradhan

One can directly store the returned output of a function in a file.

可以直接将函数的返回输出存储在文件中。

print(output statement, file=open("filename", "a"))