如何将多个用户的推文附加到单个CSV文件中

时间:2015-09-28 06:11:28

标签: python csv twitter tweepy

我正在使用tweepy尝试使用这个代码在单个CSV文件中提取最近50条多个用户的推文。使用此代码,我可以单独为所有用户制作CSV文件,但希望将它们放入单个CSV文件中。

import tweepy 
import csv

consumer_key ='XXX'
consumer_secret = 'XXX'
access_key = 'XXX'
access_secret = 'XXX'

handles_list = ["handle1", "handle2", "handle3"]

def get_all_tweets(screen_name):
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)

    recenttweets = []   
    recent_tweets = api.user_timeline(screen_name = handle, count=50)
    recenttweets.extend(new_tweets)

    Resultingtweets= [[tweet.user.name, tweet.user.screen_name, tweet.user.description, tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in recenttweets]

    with open('%s_tweets.csv' % handle, 'w', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(["User Name","Twitter_Handle","Twitter_User_Description","tweet_id","created_at","Tweet_text"])
        writer.writerows(Resultingtweets)

if __name__ == '__main__':
    for handle in handles_list:
        get_all_tweets("handles")
        print ("Done.")

1 个答案:

答案 0 :(得分:2)

您需要重新调整一些内容并且只为输出打开一个文件,以下类型的方法应该有效:

import tweepy 
import csv

consumer_key ='XXX'
consumer_secret = 'XXX'
access_key = 'XXX'
access_secret = 'XXX'

handles_list = ["handle1", "handle2", "handle3"]

def get_all_tweets(screen_name, writer):
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)

    recenttweets = []   
    recent_tweets = api.user_timeline(screen_name = handle, count=50)
    recenttweets.extend(new_tweets)

    Resultingtweets= [[tweet.user.name, tweet.user.screen_name, tweet.user.description, tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in recenttweets]

    writer.writerow(["User Name","Twitter_Handle","Twitter_User_Description","tweet_id","created_at","Tweet_text"])
    writer.writerows(Resultingtweets)

if __name__ == '__main__':
    with open('all_tweets.csv', 'w', encoding='utf-8') as f_all:
        writer = csv.writer(f_all)

        for handle in handles_list:
            get_all_tweets("handles", writer)
            print ("Done.")