Python使用os.listdir()获取文件夹文件列表时遇Unicode转义语法错误
解决Python os.listdir()的Unicode转义语法错误
你的问题出在Windows路径里的反斜杠\——在Python字符串中它是转义字符,\U会被解析为Unicode转义序列的开头,但后续字符不完整,因此触发了SyntaxError。和文件夹位置、名称无关,只需要修正路径的写法即可,以下是三种可行方案:
使用双反斜杠代替单反斜杠:把路径里的每个
\改成\\,让Python将其识别为普通反斜杠import os files = os.listdir("C:\\Users\\Alex\\Desktop\\Channel") print(files)使用原始字符串:在路径字符串前加
r,Python会忽略所有转义规则,直接按字面解析路径import os files = os.listdir(r"C:\Users\Alex\Desktop\Channel") print(files)使用正斜杠代替反斜杠:Python跨平台支持正斜杠作为路径分隔符,Windows系统也能正常识别
import os files = os.listdir("C:/Users/Alex/Desktop/Channel") print(files)
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

