Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

python - Get data from Twitter using Tweepy and store in csv file

I'm new to Python, Twitter, and Tweepy. I managed to pull data from Twitter, but I now want to store it into a CSV file.

My code is:

#!/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

This prints data out on CLI, but I want it to output to a CSV file. I tried a few different options, but it only outputted the first tweet and not all tweets.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will do the job!

I will recommend you to use csv from Python. Open a file and write to it during your loop like this:

#!/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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...