SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape错误原因及解决方法

时间:2023-03-09 06:38:51
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape错误原因及解决方法

用Python打开文件:

with open('C:\Users\PINPIN\test\file1.txt','r') as f2:
pass

运行后直接就报错了:

File "<ipython-input-23-e7225f3e179e>", line 1
with open('C:\Users\PINPIN\test\file1.txt','r') as f2:
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

意思是编解码器不能解码的字节的位置

解决方法是:

with open(r'C:\Users\PINPIN\test\file1.txt','r') as f2:
with open('C:\\Users\\PINPIN\\test\\file1.txt','r') as f2:

原因:

加r和不加''r是有区别的

'r'是防止字符转义的

如果路径中出现类似'\t'等特殊字符的话,不加r的话\t就会被转义,而加了'r'之后'\t'就能保留原有的样子

在字符串赋值的时,前面加'r'可以防止字符串在显示的时候不被转义,原理和在特殊字符前加转义字符'\'效果一致