我有以下代码(我只想尝试将关注者列表写入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()
你可能已经看到我还没有完成这个样本(还没有编写循环以获得所有前500名粉丝,或者将它们正确地写入CSV)但我得到了关闭以下错误:
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
有人能提供一些有关为何发生这种情况的见解吗?感谢。
答案 0 :(得分:1)
追溯说&#34; KeyError:0&#34;。因此,x[0]
似乎导致问题,因为它不存在。检查len(x)
。它可能为零。