首页 > 解决方案 > 我想我在 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

标签: python-3.5discord.py

解决方案


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")

推荐阅读