如何将python屏幕输出保存到文本fi

2024-05-09 14:47:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手。我需要从dict中查询条目并将结果保存到文本文件中。以下是我所拥有的:

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']

如何将打印输出保存到文本文件?


Tags: nameinimportjsonforinputageif
3条回答

你要的不是不可能的,但可能不是你真正想要的。

不要试图将屏幕输出保存到文件,只需将输出写入文件而不是屏幕。

像这样:

with open('outfile.txt', 'w') as outfile:
    print >>outfile, 'Data collected on:', input['header']['timestamp'].date()

只需将该>>outfile添加到所有打印语句中,并确保所有内容都缩进到该with语句下。


一般来说,最好使用字符串格式,而不是神奇的print逗号,这意味着您可以改用write函数。例如:

outfile.write('Data collected on: {}'.format(input['header']['timestamp'].date()))

但如果print在格式化方面已经做了您想要做的事情,那么您现在就可以坚持使用它了。


如果你有其他人写的一些Python脚本(或者更糟的是,一个你没有源代码的编译C程序)却不能进行更改呢?然后,答案是将其包装在另一个脚本中,该脚本使用^{}模块捕获其输出。再说一次,你可能不想要,但如果你想要:

output = subprocess.check_output([sys.executable, './otherscript.py'])
with open('outfile.txt', 'wb') as outfile:
    outfile.write(output)

在脚本中执行此操作的快捷方法是将屏幕输出定向到文件:

import sys 

stdoutOrigin=sys.stdout 
sys.stdout = open("log.txt", "w")

然后返回到代码末尾的输出屏幕:

sys.stdout.close()
sys.stdout=stdoutOrigin

对于简单的代码,这应该有效,但是对于复杂的代码,还有其他更正式的方法,例如使用Python logging

让我总结一下所有的答案,再加上一些。

  • 要从脚本中写入文件,Python提供的用户file I/O tools(这是f=open('file.txt', 'w')的东西。

  • 如果不想修改程序,可以使用流重定向(在windowsUnix-like systems上)。这就是python myscript > output.txt的东西。

  • 如果您想在屏幕和日志文件中同时看到输出,并且您在Unix上,并且不想修改程序,则可以使用tee commandwindows version also exists,但我从未使用过)

  • 更好的方式将所需的输出发送到屏幕、文件、电子邮件、twitter,无论是使用logging module。这里的学习曲线是所有选择中最陡峭的,但从长远来看,它将为自己付出代价。

相关问题 更多 >