Search code examples
pythonapicsvtwitter

using followers/friends methods from twitter api in python resulting in error


I have the following code (I'm just trying to write a list of followers into a CSV).

from twitter import *
from tkinter import *
import csv
import tweepy

# Auth
t = Twitter(
    auth=OAuth('Tokens/keys here')

def csvFollowers(x):
    for i in range(0, 500):
        # write 500 followers into csv
        f_id = (x[i]['users']['id_str'])
        f_screen_name = (x[i]['users']['screen_name'])
        f_name = (x[i]['users']['name'])
        f_location = (x[i]['users']['location'])

        f = csv.writer(open("TFollowers.csv", "a+"))
        f.writerow([f_id, f_screen_name, f_name, f_location])

def getFollowers():

    x = t.followers.list(screen_name="USER")
    return x

master = Tk()
#f = csv.writer(open("TFollowers.csv", "a+"))
csvFollowers(getFollowers())    
master.mainloop()

As you might see I haven't quite finished this sample yet (haven't yet written the loop to get all first 500 followers, or written them properly into the CSV) but I'm getting the following error off the bat:

Traceback (most recent call last):
  File "C:\Users\USER\Desktop\writeIdsToCsv.py", line 43, in <module>
    csvFollowers(getFollowers())
  File "C:\Users\USER\Desktop\writeIdsToCsv.py", line 15, in csvFollowers
    f_id = (x[0]['users']['id_str'])
KeyError: 0

Could anyone offer some insight as to why this is happening? Thanks.


Solution

  • The traceback says "KeyError: 0". So, it appears x[0] caused a problem because it does not exist. Check len(x). It is probably zero.