I'm trying to make the code to choose a random file from a folder and tweet it on tweeter, but i get an error

I'm on windows 10, haven't tried anything else.


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)

I expect the code to choose a picture and to post it on Twitter, but it says 'FileNotFoundError: [Errno 2] No such file or directory: '753.jpg''

Edit: It does pick a photo from the dir, but it says FileNotFoundError: [Errno 2] No such file or directory: 'numberOfFile.jpg' when it's clearly there where i set it.

2 Answers

1
user1438644 On

I have a problem with this path ='C:/Users/Name/Desktop/twitbot/home/gay'

use this in the place:

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
Mahmoud Elshahat On

you need to specify full file path and name check code below:

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)