【发布时间】:2017-11-05 09:30:19
【问题描述】:
我正在开发 tweepy 库以使用 twitter 流 API。我想将所有这些推文保存在 .txt 文件或 .csv 文件中。
//我的部分代码
def on_status(self, status):
print( status.text)
当我编写这行代码并在终端上运行 python getData.py(代码文件名)时,tweet(带有主题标签、id、http 等)将在 10 分钟左右后打印出来。
但是为了将数据保存在 .txt 文件中,当我运行 python getData.py > getData.txt 这个。花了几个小时但没有得到任何结果。
我也试过
def on_status(self, status):
with open("getData.txt","wb") as myFile:
myFile.write(status)
myFile.close()
但它给了我错误。这是所有这些错误中的a link。
同样,我尝试了 .csv 文件,但再次出现错误。
这是我的完整代码。
import tweepy
import csv
####input your credentials here
consumer_key = ' '
consumer_secret = ' '
access_token = ' '
access_token_secret = ' '
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
#create a wrapper for the API provided by twitter.
api = tweepy.API( auth )
class TwitterStreamListener(tweepy.StreamListener):
""" A listener handles tweets are the received from the stream.
This is a basic listener that just prints received tweets to stdout.
"""
def on_status(self, status):
print( status)
# Twitter error list : https://dev.twitter.com/overview/api/response-codes
def on_error(self, status_code):
if status_code == 403:
print("The request is understood, but it has been refused or access is not allowed. Limit is maybe reached")
return False
#create the stream
streamListener = TwitterStreamListener()
# Add your wrapper and your listner to the stream object
myStream = tweepy.Stream( auth = api.auth, listener = streamListener)
myStream.filter(track=['rajnathsingh'], async=True)
# myStream.filter( follow = ['135421739'])
我想将它存储在 .txt 文件的 .csv 文件中。我应该如何解决这个问题? 谢谢。
【问题讨论】:
-
请将您的完整代码和错误直接发布到问题中
-
您的连接似乎有问题,与写入文件无关。也许您已经超出了允许的请求限制。此外,如果您不附加到文件
'a'而不是open("getData.txt","wb"),则每次打开它时都会覆盖它。 -
@Peter 我尝试使用
'a'但这会给我myFile.write(status) TypeError: write() argument must be str, not Status这个错误,连接不是问题。谢谢。 -
所有错误都表明存在连接问题。
标签: python python-3.x csv twitter tweepy