每当我从文件夹中选择一个随机文件时,它就说找不到文件

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

我正在尝试使代码从文件夹中选择一个随机文件并在tweeter上发推文,但是我收到错误

我在Windows 10上,没有尝试过其他任何东西。


path ='C:/Users/Name/Desktop/twitbot/home/gay'
files = os.listdir(path)
index = random.randrange(0, len(files))

message = "Picture of the moment!"
with open(files[index], 'rb') as photo:
    twitter.update_status_with_media(status=message, media=photo)

我希望代码选择一张图片并在Twitter上发布,但是它说'FileNotFoundError:[Errno 2]没有这样的文件或目录:'753.jpg''

编辑:它确实从目录中选择了一张照片,但它说FileNotFoundError:[Errno 2]没有这样的文件或目录:'numberOfFile.jpg'当它显然在我设置它时。

python python-3.x random tweets
2个回答
1
投票

我有这个路径的问题='C:/ Users / Name / Desktop / twitbot / home / gay'

在这个地方使用这个:

import os
pth ='C:/Users/Name/Desktop/twitbot/home/gay'
pth = os.path.join(*pth.split('/'))
files = os.listdir(path)
index = random.randrange(0, len(files))

message = "Picture of the moment!"
with open(files[index], 'rb') as photo:
    twitter.update_status_with_media(status=message, media=photo)

0
投票

您需要在下面指定完整文件路径和名称检查代码:

path ='C:/Users/Name/Desktop/twitbot/home/gay'
files = os.listdir(path)
index = random.randrange(0, len(files))

message = "Picture of the moment!"
file = path + '/' + files[index]
# or you can use file = os.path.join(os.path.realpath(path), files[index])
with open(file, 'rb') as photo:
    twitter.update_status_with_media(status=message, media=photo)
© www.soinside.com 2019 - 2024. All rights reserved.