Get data from Twitter using Tweepy and save to csv file

I am new to Python, Twitter and Tweepy. I managed to get the data from Twitter, but now I want to save it in 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 outputs the data to the CLI, but I want it to be output to a CSV file. I tried several different options, but it only displayed the first tweet and not all tweets.

+4
source share
3 answers

It will do the job!

I recommend you use csv from Python. Open the file and write to it during the loop:

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

CSV, , , - , , , , ?

0

You can run the program and print the output in another file. Go to CMD and enter the
python file.py > newFile.py
output from file.py will be read in newFile.py

0
source

All Articles