想要使用tweepy将推文数据存储在.txt或.csv文件中

时间:2017-06-04 13:57:57

标签: python python-3.x csv twitter tweepy

我正在使用tweepy库来使用twitter流API。我想将所有这些推文保存在.txt文件或.csv文件中。

//我的代码的一部分

def on_status(self, status):
    print( status.text)

当我编写这行代码并在终端上运行 python getData.py (代码文件名)时,推文(带有主题标签,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文件中。我该如何解决这个问题? 谢谢。

1 个答案:

答案 0 :(得分:1)

好吧,在保存csv之前,需要先对你的推文进行编码。 它对我有用

status = tweet.text.encode('utf8')
with open('getData.txt', 'a') as myFile:     
                              writer = csv.writer(myFile)
                              writer.writerow([status])