如何将iPython笔记本的全部输出保存为.txt文件?
我已经在ipython笔记本上编写了一个从twitter抓取数据的程序。该程序将大量数据流作为输出,我想将此输出保存在.txt文件中。我该怎么做?当我打开终端时,我可以通过以下方式轻松完成: python myfile.py>file.txt如何将iPython笔记本的全部输出保存为.txt文件?,python,api,web-crawler,ipython,Python,Api,Web Crawler,Ipython,我已经在ipython笔记本上编写了一个从twitter抓取数据的程序。该程序将大量数据流作为输出,我想将此输出保存在.txt文件中。我该怎么做?当我打开终端时,我可以通过以下方式轻松完成: python myfile.py>file.txt 如何在ipython笔记本中执行相同的操作?我认为下面的代码sniplet将帮助您。 我只是将stdout更改为指向某个文件。之后的任何输出都将写入该文件 稍后,我将标准输出更改回其原始形式 import sys # Holding the origin
如何在ipython笔记本中执行相同的操作?我认为下面的代码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")
只需像平常一样写入一个文件?打开“twitter_stream.txt”,“w”作为f:for-line-in-stream:printline,file=f