我是Python的新手。我需要从字典查询项目并将结果保存到文本文件。这是我所拥有的:
import json
import exec.fullog as e
input = e.getdata() #input now is a dict() which has items, keys and values.
#Query
print 'Data collected on:', input['header']['timestamp'].date()
print '\n CLASS 1 INFO\n'
for item in input['Demographics']:
if item['name'] in ['Carly', 'Jane']:
print item['name'], 'Height:', item['ht'], 'Age:', item['years']
for item in input['Activity']:
if item['name'] in ['Cycle', 'Run', 'Swim']:
print item['name'], 'Athlete:', item['athl_name'], 'Age:', item['years']
Run Code Online (Sandbox Code Playgroud)
如何将打印的输出保存到文本文件?
met*_*ure 13
abarnert
's answer非常好,pythonic。另一个完全不同的路线(不是在 python 中)是让 bash 为你做这件事:
$ python myscript.py > myoutput.txt
Run Code Online (Sandbox Code Playgroud)
这通常适用于将 cli 程序(python、perl、php、java、二进制或其他)的所有输出放入一个文件中,有关更多信息,请参阅如何将 bash 脚本的整个输出保存到文件中。
如果您希望输出转到标准输出和文件,您可以使用 tee:
$ python myscript.py | tee myoutput.txt
Run Code Online (Sandbox Code Playgroud)
有关 tee 的更多信息,请参阅:如何将输出重定向到文件和标准输出
在脚本中执行此操作的一种快速而肮脏的技巧是将屏幕输出定向到文件:
import sys
stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")
Run Code Online (Sandbox Code Playgroud)
然后返回到代码末尾的输出到屏幕:
sys.stdout.close()
sys.stdout=stdoutOrigin
Run Code Online (Sandbox Code Playgroud)
这应该适用于简单的代码,但是对于复杂的代码,还有其他更正式的方法,例如使用Python日志记录。
让我总结所有答案并添加更多答案。
要从脚本中写入文件,需要使用Python提供的用户文件I / O工具(这是f=open('file.txt', 'w')
东西。
如果不想修改程序,则可以使用流重定向(在Windows和类似Unix的系统上)。这是python myscript > output.txt
东西。
如果您想同时在屏幕和日志文件中看到输出,并且如果您使用的是Unix,并且不想修改程序,则可以使用tee命令(Windows版本也存在,但是我有没用过)
你所要求的并不是不可能的,但它可能不是你真正想要的。
不要尝试将屏幕输出保存到文件,只需将输出写入文件而不是屏幕。
像这样:
with open('outfile.txt', 'w') as outfile:
print >>outfile, 'Data collected on:', input['header']['timestamp'].date()
Run Code Online (Sandbox Code Playgroud)
只需将其添加>>outfile
到所有打印语句中,并确保所有内容都在该with
语句下缩进。
更一般地说,最好使用字符串格式而不是魔术print
逗号,这意味着您可以使用该write
函数。例如:
outfile.write('Data collected on: {}'.format(input['header']['timestamp'].date()))
Run Code Online (Sandbox Code Playgroud)
但如果print
就格式化而言已经完成了您想要的操作,那么您现在可以坚持使用它。
如果您有其他人编写的一些 Python 脚本(或者更糟糕的是,您没有源代码的已编译 C 程序)并且无法进行此更改,该怎么办?那么答案是将其包装在另一个捕获其输出的脚本中,以及subprocess
模块。同样,您可能不希望这样,但如果您这样做:
output = subprocess.check_output([sys.executable, './otherscript.py'])
with open('outfile.txt', 'wb') as outfile:
outfile.write(output)
Run Code Online (Sandbox Code Playgroud)
这是 python 3+ 中一个非常简单的方法:
f = open('filename.txt', 'w')
print('something', file = f)
Run Code Online (Sandbox Code Playgroud)
^从这个答案中发现:/sf/answers/287763451/
归档时间: |
|
查看次数: |
51454 次 |
最近记录: |