简体   繁体   中英

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. The program gives enormous streams of data as output and I want to save this output in .txt file. 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?

I think below code sniplet will help you. I am simply changing stdout to point to some file. 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") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM