将打印输出定向到 .txt 文件 [英] Directing print output to a .txt file
问题描述
有没有办法在python中将所有打印输出保存到txt文件中?假设我的代码中有这两行,我想将打印输出保存到一个名为 output.txt
的文件中.
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
.
print ("Hello stackoverflow!")
print ("I have a question.")
我希望 output.txt
文件包含
Hello stackoverflow!
I have a question.
推荐答案
给 print
一个 file
关键字参数,其中参数的值是一个文件流.我们可以使用 open
函数创建一个文件流:
Give print
a file
keyword argument, where the value of the argument is a file stream. We can create a file stream using the open
function:
print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))
From the Python documentation about print
:
file
参数必须是一个带有 write(string)
方法的对象;如果它不存在或 None
,将使用 sys.stdout
.
The
file
argument must be an object with awrite(string)
method; if it is not present orNone
,sys.stdout
will be used.
和 open
的文档:
And the documentation for open
:
打开file
并返回一个对应的文件对象.如果无法打开文件,则会引发 OSError
.
Open
file
and return a corresponding file object. If the file cannot be opened, anOSError
is raised.
"a"
作为 open
的第二个参数的意思是追加";- 换句话说,文件的现有内容不会被覆盖.如果您希望文件被覆盖,请使用 "w"
.
The "a"
as the second argument of open
means "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"
.
多次使用 open
打开文件对于性能来说并不理想.理想情况下,您应该打开它并为其命名,然后将该变量传递给 print
的 file
选项.您必须记住之后关闭文件!
Opening a file with open
many times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print
's file
option. You must remember to close the file afterwards!
f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()
对此还有一个语法快捷方式,即 with
块.这将在块的末尾为您关闭您的文件:
There's also a syntactic shortcut for this, which is the with
block. This will close your file at the end of the block for you:
with open("output.txt", "a") as f:
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
这篇关于将打印输出定向到 .txt 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!