python-3.5 - 我想我在 discord.py 机器人的逻辑中错误地添加了图像文件夹的路径
问题描述
我试图让机器人从我的电脑上的一个文件夹中随机选择一个图像来响应:
if message.content == "look at this":
imgList = os.listdir("C:\Users\Alien\Desktop\BOTS\TAL\IMAGES")
imgString = random.choice(imgList)
path = "C:\Users\Alien\Desktop\BOTS\TAL\IMAGES" + imgString
await client.send_file(message.channel, path)
这是一个较长的 .py 文件的一部分,其中包含许多不同的代码,这些代码都可以与必要的 intros/outros 等一起正常工作
在我添加它之前它运行良好,但现在当我尝试运行它时会打印:
C:\Users\Alien\PycharmProjects\tal-1.0\venv\Scripts\python.exe C:/Users/Alien/PycharmProjects/tal-1.0/tal-1.0.py
File "C:/Users/Alien/PycharmProjects/tal-1.0/tal-1.0.py", line 27
imgList = os.listdir("C:\Users\Alien\Desktop\BOTS\TAL\IMAGES")
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
Process finished with exit code 1
解决方案
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
这告诉你在位置 2-3 有一个转义字符错误,它们是字符\U
\
是字符串的转义字符。它允许您在单引号字符串中包含单引号之类的内容:var = 'you\'re'
将保留单引号而不关闭字符串。
您\
在字符串中使用了转义字符(您正在这样做,因为它是文件系统路径的一部分)。所以它试图解码下一个字符,U
,它不知道该怎么做,因为它不需要被转义。
相反,您需要转义转义字符。你需要\\
在你拥有的每个地方写下\
。
您的解决方案在所有路径中都需要这样的东西:
imgList = os.listdir("C:\\Users\\Alien\\Desktop\\BOTS\\TAL\\IMAGES")
推荐阅读
- python - 如何在keras中设置嵌入层名称
- mysql - MySQL - 仅获取最近的先前记录,而不是所有先前的记录
- class-diagram - 类图中的什么关系是合适的?
- python - 如何在不删除 unicode 的情况下使用 shell 中的 json.tool 来验证和打印语言文件?
- error-handling - 如何处理来自 reqMktData 调用的错误
- angular - 在失败测试中测试 ngrx/影响成功操作
- c# - Winforms C#中需要jQuerify CEF浏览器的解决方案
- docker - Docker 上的 Rviz 核心转储
- python - 为什么python安装sha256总是失败?
- numpy - 了解一维向量上的 np.matmul