import os# 列出指定目录中的所有文件和子目录files = oslistdirCUsersLenovoDesktopcodeAndTxtbendibaofor file in files # 解码文件名 decoded_file = fileencodelatin1decodegbk printdecoded_file用中文回答报错SyntaxError unicode
这个错误是因为在字符串中使用了反斜杠"\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)
这样就可以正常运行了。
原文地址: http://www.cveoy.top/t/topic/iMLo 著作权归作者所有。请勿转载和采集!