python - 从目录中选择随机文件时出错
问题描述
我正在尝试从目录中选择一个随机的 .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
解决方案
仅返回文件名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)
推荐阅读
- python - If x == y: print z - 为什么我的代码不打印?
- angular - 如何让验证器触发或获取验证器内部的正确控件?
- flutter - 照片被无限像素溢出
- swift - 如何使我的泛型参数符合 Swift 中的 OR 以及如何找到参数的构造?
- typescript - 泛型类的构造函数中可选字段的默认值
- google-play - 从许可证 apk 迁移到应用内购买 - 如何迁移现有许可证所有者?
- amazon-web-services - 如何获取 .net core lambda 的 event.action?
- java - 如何使用约束布局将回收器视图项设置为屏幕宽度的一半?
- azure - azure 服务主体:在 jenkins 管道中的访问被拒绝在命令行中很好(是否使用插件)
- batch-file - 如何将路径与字符串批量组合?