使用Tweepy从Twitter获取数据并将其存储在csv文件中

use*_*317 4 python csv twitter tweepy python-2.7

我是Python,Twitter和Tweepy的新手。我设法从Twitter提取数据,但现在我想将其存储到CSV文件中。

我的代码是:

#!/usr/bin/python

import tweepy

auth = tweepy.auth.OAuthHandler('XXXXXX', 'XXXXXXX'
auth.set_access_token('XXX-XXX', 'XXX'

api = tweepy.API(auth)
for tweet in tweepy.Cursor(api.search,
                           q="google",
                           since="2014-02-14",
                           until="2014-02-15",
                           lang="en").items():
    print tweet.created_at, tweet.text
Run Code Online (Sandbox Code Playgroud)

这会在CLI上打印数据,但我希望将其输出到CSV文件。我尝试了几种不同的选项,但只输出了第一条推文,而不是所有推文。

Roy*_*rie 7

这样就可以了!

我建议您使用Python的csv。打开一个文件并在循环期间将其写入,如下所示:

#!/usr/bin/python
import tweepy
import csv #Import csv
auth = tweepy.auth.OAuthHandler('XXXXXX', 'XXXXXXX')
auth.set_access_token('XXX-XXX', 'XXX')

api = tweepy.API(auth)

# Open/create a file to append data to
csvFile = open('result.csv', 'a')

#Use csv writer
csvWriter = csv.writer(csvFile)

for tweet in tweepy.Cursor(api.search,
                           q = "google",
                           since = "2014-02-14",
                           until = "2014-02-15",
                           lang = "en").items():

    # Write a row to the CSV file. I use encode UTF-8
    csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8')])
    print tweet.created_at, tweet.text
csvFile.close()
Run Code Online (Sandbox Code Playgroud)

  • CSV对我来说是空的。 (2认同)