有没有办法将所有打印输出保存到 python 中的 txt 文件?假设我的代码中有这两行,我想将打印输出保存到名为 output.txt
的文件中。
print ("Hello stackoverflow!")
print ("I have a question.")
我希望 output.txt
文件包含
Hello stackoverflow!
I have a question.
最佳答案
给 print
一个 file
关键字参数,其中参数的值是文件流。最佳实践是使用 with
block 使用 open
函数打开文件,这将确保文件在 block 结束时为您关闭:
with open("output.txt", "a") as f:
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
来自 Python documentation about print
:
The
file
argument must be an object with awrite(string)
method; if it is not present orNone
,sys.stdout
will be used.
还有 the documentation for open
:
Open
file
and return a corresponding file object. If the file cannot be opened, anOSError
is raised.
"a"
作为open
的第二个参数的意思是“追加”——换句话说,文件的现有内容不会被覆盖。如果您希望文件在 with
block 的开头被覆盖,请使用 "w"
。
with
block 很有用,否则,您需要记住自己关闭文件,如下所示:
f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()
关于python - 将打印输出定向到 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36571560/