Amohanty
Amohanty

Reputation: 107

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?

Upvotes: 0

Views: 2619

Answers (1)

Jyotirmay
Jyotirmay

Reputation: 1825

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") 

Upvotes: 2

Related Questions