我想从字典中查询项目并将打印输出保存到文本文件中。
这是我所拥有的:
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'])
abarnert
的答案非常好并且Pythonic。另一个完全不同的路线(不在 python 中)是让 bash 为你做这件事:
$ python myscript.py > myoutput.txt
这通常可以将 cli 程序(python、perl、php、java、二进制文件或其他)的所有输出放入一个文件中,请参阅如何将 bash 脚本的整个输出保存到文件 https://stackoverflow.com/questions/17554018/how-to-save-entire-output-of-bash-script-to-file了解更多。
如果您希望输出到标准输出and对于该文件,您可以使用 tee:
$ python myscript.py | tee myoutput.txt
有关 T 恤的更多信息,请参阅:如何将输出重定向到文件和标准输出 https://stackoverflow.com/questions/418896/how-to-redirect-output-to-a-file-and-stdout
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)