将datascrape推送到csv(tweeepy,python)。如果文件已存在,如何追加:

时间:2017-05-01 11:54:59

标签: python python-2.7 csv tweepy

我有以下代码:

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中。这可能/有没有人有任何想法?如果这是不可能的,有没有人知道如何在这里写if else函数:如果文件存在,打印随机条目,否则刮,存储,然后打印随机条目。任何hellp表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:2)

而不是' 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)