2017-09-23 8 views
-1

ipython 노트북의 트위터에서 데이터를 크롤링하는 프로그램을 작성했습니다. 이 프로그램은 엄청난 양의 데이터 스트림을 출력하고이 출력을 .txt 파일로 저장하려고합니다. 어떻게해야합니까? 터미널을 열면 다음과 같이 쉽게 할 수 있습니다 : python myfile.py> file.txt ipython 노트북에서 어떻게 똑같은 작업을 수행합니까?iPython 노트북의 전체 출력을 어떻게 .txt 파일로 저장할 수 있습니까?

+0

평소처럼 파일에 쓰기 만 하시겠습니까? – erip

+0

'with open ('twitter_stream.txt', 'w') f : 스트림의 줄 : print (line, file = f)' – erip

답변

1

다음 코드 스 니펫이 도움이 될 것이라고 생각합니다. 일부 파일을 가리 키기 위해 단순히 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")