我在 Windows 7 机器上使用 Python 3.1。

看一个答案上一个问题,我尝试使用"编解码器"模块给我一点运气。这里有几个例子:

>>> g = codecs.open("C:\Users\Eric\Desktop\beeline.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#39>, line 1)

>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#40>, line 1)

>>> g = codecs.open("C:\Python31\Notes.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-12: malformed \N character escape (<pyshell#41>, line 1)

>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#44>, line 1)

我的最后一个想法是,我认为Windows"翻译"了一些文件夹,例如"用户"文件夹,将其"翻译"到俄语(尽管键入"用户"仍然是正确的路径),所以我尝试了它Python31文件夹。仍然没有运气。有任何想法吗?

答案

问题是字符串

"C:\Users\Eric\Desktop\beeline.txt"

这里,\U"C:\Users…启动八个字符的Unicode逃生,例如\U00014321。在您的代码中,逃生之后是角色" S",这是无效的。

您要么需要复制所有反弹:

"C:\\Users\\Eric\\Desktop\\beeline.txt"

或将字符串前缀r(生产一个原始字符串):

r"C:\Users\Eric\Desktop\beeline.txt"

来自: stackoverflow.com