如何将iPython笔记本的整个输出保存为.txt文件?
问题描述:
我已经写了一个程序,在IPython的笔记本从Twitter抓取数据。该程序提供了大量的数据流作为输出,我想将这个输出保存为.txt文件。我该怎么做?当我打开我的终端,我可以很容易地做到这一点的: 蟒蛇myfile.py> file.txt的 如何做IPython的笔记本是一回事吗?如何将iPython笔记本的整个输出保存为.txt文件?
答
我想下面的代码sniplet会帮助你。 我只是将stdout更改为指向某个文件。不管输出结果如何,都会写入该文件。
后来我改变标准输出恢复到原来的形态。
import sys
# Holding the original output object. i.e. console out
orig_stdout = sys.stdout
# Opening the file to write file deletion logs.
f = open('file.txt', 'a+')
# Changing standard out to file out.
sys.stdout = f
# Any print call in this function will get written into the file.
myFunc(params)
# This will write to the file.
print("xyz")
# Closing the file.
f.close()
# replacing the original output format to stdout.
sys.stdout = orig_stdout
# This will print onto the console.
print("xyz")
只需写入像你一样的文件通常会? – erip
'具有开放( 'twitter_stream.txt', 'W')为f: 在流线:打印(线,文件= F)' – erip