我正在使用Twython制作一个从文件夹中发布随机图像的机器人,这是代码!
from twython import Twython
import glob
import random
app_key = "XXX"
app_secret = "XXX"
oauth_token = "XXX"
oauth_token_secret = "XXX"
twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
def RandomImageTwitt(folder):
#Takes the folder where your images are as input
images = glob.glob(folder + "*")
image_open = open(images[random.randint(0,len(images))-1])
#Tweeting
image_ids = twitter.upload_media(media=image_open)
twitter.update_status(status='hello this is a status', media_ids=image_ids['media_id'])
RandomImageTwitt("/home/Pi/Bots/Pictures/")
好的,当我使用python script.py时,它会返回此错误:
Traceback (most recent call last):
File "script.py", line 20, in <module>
RandomImageTwitt("/home/Pi/Bots/Pictures/")
File "script.py", line 14, in RandomImageTwitt
image_open = open(images[random.randint(0,len(images))-1])
IndexError: list index out of range
我是Python的初学者,如果可以提供帮助,我的所有文件都会像这样存储:1.jpg,2.jpg,3.jpg ...每个文件都在jpg中,列表从1开始
谢谢!
答案 0 :(得分:1)
确保images
不为空。
random.choice
更好(不需要自己计算索引,更容易阅读):
image_open = open(random.choice(images))
如果序列为空, random.choice
也会引发IndexError
。