You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Twitter图片机器人出现FileNotFoundError问题求助

问题解决:FileNotFoundError 找不到图片文件

错误原因

os.listdir() 只会返回目标文件夹里的文件名,不包含完整路径。当你调用 api.simple_upload(image) 时,Python会在当前脚本的工作目录下寻找这个文件,而不是你指定的图片文件夹,所以会提示找不到文件。

修复方案

方法1:提前拼接完整文件路径

把图片文件夹路径单独存储,然后将每个文件名和文件夹路径拼接成完整路径:

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)

# 定义图片文件夹路径
image_folder = "D:/Trevor/Pictures/Reference/Zimmerman"
# 获取所有图片的完整路径
images = [os.path.join(image_folder, img) for img in os.listdir(image_folder)]

# 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)

方法2:切换工作目录到图片文件夹

先切换当前工作目录到图片文件夹,这样直接用文件名就能找到文件:

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)

# 切换工作目录到图片文件夹
image_folder = "D:/Trevor/Pictures/Reference/Zimmerman"
os.chdir(image_folder)
# 获取文件夹内的文件名
images = os.listdir()

# 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)

额外建议

可以添加过滤逻辑,只保留图片格式的文件(比如.jpg, .png),避免误选非图片文件:

valid_extensions = ('.jpg', '.jpeg', '.png', '.gif')
images = [os.path.join(image_folder, img) for img in os.listdir(image_folder) if img.lower().endswith(valid_extensions)]

内容的提问来源于stack exchange,提问作者KnowNothingNoNothing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 10:13:18