发布图像的Python Twitter 机器人找不到图像

问题描述 投票:0回答:1

我正在尝试创建一个 python twitter 机器人,它使用 Tweepy api.simple_upload 每八小时从桌面上的文件夹中发布一张随机图像。但是,我收到一条错误消息“FileNotFoundError:[Errno 2]没有这样的文件或目录:'8507_wild Five.jpg'”。它说尚未找到文件但显示标题,我不明白。

这是代码:

import tweepy
import os
import time
import random

# Set up your Twitter API credentials
consumer_key = '~~~'
consumer_secret = '~~~'
access_token = '~~~'
access_token_secret = '~~~'

# Authenticate to the Twitter API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

# Get a list of all the images in the specified folder
images = os.listdir("D:/Trevor/Pictures/Reference/Zimmerman")

# Set the interval for uploading images (in seconds)
interval = 8 * 60 * 60  # 8 hours

while True:
    # Select a random image from the list
    image = random.choice(images)

    # Upload the image to Twitter
    api.simple_upload(image)

    # Wait for the specified interval before uploading the next image
    time.sleep(interval)

我得到的回溯是:

Traceback (most recent call last):
  File "D:\Trevor\Downloads\TweepyV2Images-main\ZbotV10.py", line 28, in <module>
    api.simple_upload(image)
  File "C:\Python38\lib\site-packages\tweepy\api.py", line 46, in wrapper
    return method(*args, **kwargs)
  File "C:\Python38\lib\site-packages\tweepy\api.py", line 3596, in simple_upload
    files = {'media': stack.enter_context(open(filename, 'rb'))}
FileNotFoundError: [Errno 2] No such file or directory: '8507_wildfive.jpg'
[Finished in 316ms]

如有任何帮助,我们将不胜感激。

python twitter bots tweepy
1个回答
0
投票

os.listdir
函数不返回完整路径,仅返回相对于调用它的目录的路径。

例如,如果有一个文件

a/b/c.txt
并且您调用
os.listdir("/a/b")
,那么您的输出将不是
["/a/b/c.txt"]
,而只是
["c.txt"]

要获取图像的完整路径,请尝试:

image = "D:/Trevor/Pictures/Reference/Zimmerman/" + random.choice(images)
© www.soinside.com 2019 - 2024. All rights reserved.