首页 > 解决方案 > 从目录中选择随机文件时出错

问题描述

我正在尝试从目录中选择一个随机的 .PNG 文件 - 有 5 个 PNG 文件(1,2,3,4,5/png)

Python 版本是 3.8.2

这是我的代码:

import os
import random

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

但我收到一个关于“没有这样的文件”的错误

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

标签: pythonfilerandom

解决方案


仅返回文件名os.listdir(),而您的users_setPhoto()调用将需要完整路径。

尝试使用os.path.join()将返回的文件名与根路径连接起来。

例如 ...

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

推荐阅读