Datascrape twitter 到 csv(tweeepy,python)。如果文件已存在,如何追加:

Datascrape twitter into csv (tweeepy, python). How to append if file already exists:

我有以下代码:

import tweepy #https://github.com/tweepy/tweepy
import csv
import random

#Twitter API credentials
consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""

twitname = raw_input("Enter desired twitter account from which a tweet will be selected to act as inspiration for the poem: ")




def get_all_tweets(screen_name):
    #Twitter only allows access to a users most recent 3240 tweets with this method

    #authorize twitter, initialize tweepy
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)

    #initialize a list to hold all the tweepy Tweets
    alltweets = []  

    #make initial request for most recent tweets (200 is the maximum allowed count)
    new_tweets = api.user_timeline(screen_name = screen_name,count=200)

    #save most recent tweets
    alltweets.extend(new_tweets)

    #save the id of the oldest tweet less one
    oldest = alltweets[-1].id - 1

    #keep grabbing tweets until there are no tweets left to grab
    while len(new_tweets) > 0:
        print "getting tweets before %s" % (oldest)

        #all subsiquent requests use the max_id param to prevent duplicates
        new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)

        #save most recent tweets
        alltweets.extend(new_tweets)

        #update the id of the oldest tweet less one
        oldest = alltweets[-1].id - 1

        print "...%s tweets downloaded so far" % (len(alltweets))

    #transform the tweepy tweets into a 2D array that will populate the csv 
    outtweets = [[tweet.text.encode("utf-8")] for tweet in alltweets]

    #write the csv  
    with open('%s_tweets.csv' % screen_name, 'wb') as f:
        writer = csv.writer(f)
        writer.writerow(["text"])
        writer.writerows(outtweets)

    pass


if __name__ == '__main__':
    #pass in the username of the account you want to download
    get_all_tweets(twitname)




spamReader = csv.reader(open(twitname + '_tweets.csv', 'r'))

twitterinsp = sum([i for i in spamReader],[]) #To flatten the list
print(random.choice(twitterinsp))

目前它抓取最新的推文,将它们存储在一个 csv 文件中,然后显示一个随机条目。我想要做的是拥有它,所以如果 csv 文件已经存在,它会将新推文附加到已经存在的 csv 中。这是 possible/does 有人有什么想法吗?如果这不可能,有谁知道我将如何在此处编写 if else 函数:如果文件存在,则打印随机条目,否则抓取、存储,然后打印随机条目。任何帮助表示赞赏。谢谢!

而不是 'wb' 你使用 'ab'

with open('%s_tweets.csv' % screen_name, 'ab') as f:

文件模式:https://www.programiz.com/python-programming/file-operation

Mode    Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)