如何将python屏幕输出保存到文本文件 [英] How to save python screen output to a text file
问题描述
我想从字典中查询项目并将打印的输出保存到文本文件中.
I'd like to query items from a dict and save the printed output to a text file.
这是我所拥有的:
import json
import exec.fullog as e
inp = e.getdata() #inp now is a dict() which has items, keys and values.
#Query
print('Data collected on:', inp['header']['timestamp'].date())
print('\n CLASS 1 INFO\n')
for item in inp['Demographics']:
if item['name'] in ['Carly', 'Jane']:
print(item['name'], 'Height:', item['ht'], 'Age:', item['years'])
for item in inp['Activity']:
if item['name'] in ['Cycle', 'Run', 'Swim']:
print(item['name'], 'Athlete:', item['athl_name'], 'Age:', item['years'])
推荐答案
让我总结一下所有的答案并补充一些.
Let me summarize all the answers and add some more.
要从脚本中写入文件,用户 文件 I/OPython 提供的工具(这是
f=open('file.txt', 'w')
的东西.
如果不想修改你的程序,你可以使用流重定向(都在 windows 和 类 Unix 系统).这是 python myscript >output.txt
东西.
If don't want to modify your program, you can use stream redirection (both on windows and on Unix-like systems). This is the python myscript > output.txt
stuff.
如果您想在屏幕和日志文件中看到两者的输出,并且如果您使用的是 Unix,并且您不想修改您的程序,您可以使用 tee 命令(windows版本也存在,不过我没用过)
If you want to see the output both on your screen and in a log file, and if you are on Unix, and you don't want to modify your program, you may use the tee command (windows version also exists, but I have never used it)
这篇关于如何将python屏幕输出保存到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!