2017-09-23 3 views
-1

私はipythonノートブックのtwitterからデータをクロールするプログラムを書いています。プログラムは、出力として膨大なデータストリームを与え、この出力を.txtファイルに保存したい。どうすればいいのですか?私が端末を開いたら、私は簡単にこれを行うことができます: python myfile.py> file.txt ipythonノートブックで同じことをするにはどうすればいいですか?iPythonノートブックの出力全体を.txtファイルとして保存するにはどうしたらいいですか?

+0

通常のようにファイルに書き込みますか? (line、file = f) ' – erip

+0

' with open( 'twitter_stream.txt'、 'w')をf: として出力します。 – erip

答えて

1

私は以下のコードスニペットが役立つと思います。 私は単にstdoutをいくつかのファイルを指すように変更しています。それ以降の出力があれば、そのファイルに書き込まれます。

後で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") 
関連する問題