Python 文件路径错误: 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
解决 Python 文件路径错误: 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
这个错误通常发生在使用 Python 的 os.listdir() 函数列出文件时,因为在字符串中使用了反斜杠 '\U',而 Python 中 '\U' 代表一个 Unicode 字符的转义序列。
为了避免这个错误,可以在字符串前面加上 'r',表示原始字符串,让反斜杠不进行转义。修改代码如下:
import os
# 列出指定目录中的所有文件和子目录
files = os.listdir(r'C:\Users\Lenovo\Desktop\codeAndTxt\bendibao')
for file in files:
# 解码文件名
decoded_file = file.encode('latin1').decode('gbk')
print(decoded_file)
解释:
r'C:\Users\Lenovo\Desktop\codeAndTxt\bendibao':添加 'r' 标识字符串为原始字符串,避免反斜杠进行转义。file.encode('latin1').decode('gbk'):将文件名称从 latin1 编码转换为 gbk 编码,以确保在中文环境下能够正确显示文件名。
注意: 如果您的文件路径中包含其他特殊字符,也需要使用类似的方法进行转义。
希望这篇文章能帮助您解决 Python 文件路径错误的问题。
原文地址: https://www.cveoy.top/t/topic/qsXx 著作权归作者所有。请勿转载和采集!