Gеtting an error while choosing random file from directory

Viewed 129

I am trying to choose a random .PNG file from directory - there are 5 PNG files (1,2,3,4,5/png)

Python version is 3.8.2

Here is my code:

import os
import random

file_path = random.choice(os.listdir(r"C:/Users/katherine/Desktop/testphotos"))
client.users_setPhoto(image=file_path)

But I get an error something about "there is no such file"

Traceback (most recent call last):     
File "C:/Users/katherine/Desktop/testcode/main.py", line 14, in <module>
        client.users_setPhoto(image=file_path)     
File "C:\Users\katherine\AppData\Local\Programs\Python\Python38-32\lib\site-packages\slack\web\client.py", line 1638, in users_setPhoto
        return self.api_call("users.setPhoto", files={"image": image}, data=kwargs)     
File "C:\Users\katherine\AppData\Local\Programs\Python\Python38-32\lib\site-packages\slack\web\base_client.py", line 171, in api_call
        return self._event_loop.run_until_complete(future)     
File "C:\Users\katherine\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 616, in run_until_complete
        return future.result()     
File "C:\Users\katherine\AppData\Local\Programs\Python\Python38-32\lib\site-packages\slack\web\base_client.py", line 207, in _send

f = open(v.encode("ascii", "ignore"), "rb")  

FileNotFoundError: [Errno 2] No such file or directory: b'3.png'

Process finished with exit code 1
2 Answers

Only the filename is returned from os.listdir(), whereas your users_setPhoto() call will require the full path.

Try using os.path.join() to join the returned filename with the root path.

For example ...

path = 'C:/Users/katherine/Desktop/testphotos'
file_path = os.path.join(path, random.choice(os.listdir(path)))
client.users_setPhoto(image=file_path)

@S3DEV's answer is to the point, but I would use glob instead.

import glob
import random


path = r'C:/Users/katherine/Desktop/testphotos'
chosen_photo = random.choice(glob.glob(path + r'/*.png'))
client.users_setPhoto(image=chosen_photo)

I think glob is better here because it results in cleaner code (returns absolute path out of the box) and you can also specify the file extension in case you have other stuff in the folders too.

An additional positive side effect is that you can even make it recursive to look inside the folders of the given path as well.

Related