如何将其写入文件?我已实现Twitter流API(Python),但它只打印在控制台上
from getpass import getpass
from textwrap import TextWrapper
import tweepy
import time
class StreamWatcherListener(tweepy.StreamListener):
status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')
def on_status(self, status):
try:
print self.status_wrapper.fill(status.text)
print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source)
except:
# Catch any unicode errors while printing to console
# and just ignore them to avoid breaking application.
pass
def on_error(self, status_code):
print 'An error has occured! Status code = %s' % status_code
return True # keep stream alive
def on_timeout(self):
print 'Snoozing Zzzzzz'
username="abc"
password="abc"
auth = tweepy.BasicAuthHandler(username, password)
listener = StreamWatcherListener()
stream=tweepy.Stream(auth,listener)
stream.filter(locations=[-122.75,36.8,-121.75,37.8,-74,40,-73,41])
这段代码只是把内容打印到控制台上。但是如果我想做更多的事情呢?我使用的库可以在这里找到。
4 个回答
0
不要使用打印输出,改为写入文件。
file = open("myNewFile")
file.write("hello")
0
请注意,你几乎不需要做任何改动就可以把内容打印到一个文件里:
import sys
sys.stdout = open('myFile', 'w')
print 'hello'
这样就会把“hello”写入到myFile这个文件中。
2
你正在使用打印语句。
打开一个文件,把你在控制台上打印的内容写入这个文件。
在你的代码中
class StreamWatcherListener(tweepy.StreamListener):
status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')
def __init__(self, api=None):
self.file = open("myNewFile")
super(StreamWatcherListener, self).__init__(api)
....