python - 将打印输出定向到 .txt 文件

标签 python python-3.x

有没有办法将所有打印输出保存到 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 a write(string) method; if it is not present or None, sys.stdout will be used.

还有 the documentation for open :

Open file and return a corresponding file object. If the file cannot be opened, an OSError 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/

相关文章:

python - ubuntu 服务器上的文件写入权限

python - 用 Python 计算分子化合物中的元素数量(如果可能的话递归)?

python-3.x - 在 Tkinter 标签内循环 OpenCV 图像 - 使用 esp32-cam

python - 列表2> sum13编码 bat 问题: 'int' object is not iterable

python - 忽略 subprocess.Popen 的输出

python - Python覆盖范围针对Docker中的同一服务在本地运行测试

python - 如何在提取包含多个值的 CSV 文件后构建实例

python - Scrapy - 悄悄地丢下一个元素

python - 为什么 Python 3 比 Python 2 慢很多?

python-3.x - 冒号(:) do in this code do?