打开文件时候遇到报错
遇到的报错如下:
SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape
目的:使用绝对路径(Absolute path)打开文件:
(unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape (, line 1)pylint(syntax-error)
原因是:f = open(‘C:\Users\xuanq\Documents\pytest\py.tech\scores.txt’)
代码中的“\”在Python中表示转义.
不让“\”转义可以解决问题:
方式1:显式声明字符串不用转义
在字符串前加上r或R,即:f = open(R’C:\Users\xuanq\Documents\pytest\py.tech\scores.txt’),
r或R在python中表示不转义后面的字符串。
方式2:转义的方式
在“\”前加上""用以转义。即:f = open(‘C:\Users\xuanq\Documents\pytest\py.tech\scores.txt’)
方式3:使用linux的路径
将“\”换为“/”,即:f = open(‘C:/Users/xuanq/Documents/pytest/py.tech/scores.txt’)
相关python字符串前缀的内容:
1、在字符串前加上r或R表示该字符串是非转义的原始字符串。
2、在字符串前加上u或U表示该字符串是unicode字符串。
windows中的路径是反斜杠\,然而反斜杠\在python中有着转义字符的意义,
所以在py文件中写windows文件路径的时候,要特别注意反斜杠\的使用。
方式3:使用linux的路径 的方法
linux和windows通用的,所以推荐用这个表达方式。