[英]How can I save my entire output from iPython notebook as .txt file?
I have written a program to crawl data from twitter in ipython notebook. 我已经编写了一个程序来在ipython Notebook中从Twitter爬网数据。 The program gives enormous streams of data as output and I want to save this output in .txt file. 该程序将大量数据流作为输出,我想将此输出保存在.txt文件中。 How do I do it? 我该怎么做? When I open my terminal,I can easily do it by: python myfile.py>file.txt How do I do the same thing in ipython notebook? 当我打开终端时,我可以通过以下方式轻松地做到这一点:python myfile.py> file.txt如何在ipython Notebook中做同样的事情?
I think below code sniplet will help you. 我认为下面的代码片段将为您提供帮助。 I am simply changing stdout to point to some file. 我只是在更改stdout以指向某个文件。 Whatever the output be after that will get written into that file. 之后的任何输出将被写入该文件。
Later I am changing the stdout back to its original form. 稍后,我将标准输出变回其原始形式。
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.