首页 > 解决方案 > 进程被杀死/完成后出现将 python print() 的输出写入文件

问题描述

我的代码中有几个 print() 语句。我想在一夜之间运行代码并让它们写入文件。我尝试将输出重定向到文件:

python mycode.py >> log.txt

在 python 进程运行时,我看不到任何写入文件的内容。当我终止进程并打开日志文件时,我在其中找到了输出。

当我在每个打印语句中明确指定文件句柄时,也出现了类似的行为:

output_file = open('log.txt','w')
print('blablabla', file=output_file)

我怎样才能print立即写入文件?我错过了什么吗?

标签: pythonwindowsfilefile-io

解决方案


你能试试这个并告诉我它是否立即更新。我总是在PyCharm中使用这种语法。我希望它也适用于你。

如果你想一次插入一堆数据

with open("log.txt", 'w') as test:
    print ("hello world!", file=test)

如果要向 中插入数据.txt,请执行一些处理,然后再次返回以将更多数据添加到.txt

test = open("log.txt", 'w')
print ("hello world!", file=test)
#==== Do some processes ====
print("This's the end of the file")
test.close()

推荐阅读