报错代码:
SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape
infile=open("C:\Users\HP\Desktop\三国演义.txt","r")
data=infile.read()
print(data)
该错误的原因是:infile=open(“C:\Users\HP\Desktop\三国演义.txt”,“r”)这行代码中的“\””在Python中表示转义.
解决方法当然就是不让“\”代表转义。所以可以:
1、在字符串前加上r或R,即:infile=open(r’C:\Users\HP\Desktop\三国演义.txt’) ,其中r或R在python中表示一个不转义的字符串。
2、在“\”前加上“\”实现转义。即:infile=open(“C:\Users\HP\Desktop\三国演义.txt”)
3、将“\”换为“/”,即:infile=open(“C:/Users\HP\Desktop\三国演义.txt”)
最后:补充一下python字符串前缀的知识:
1、在字符串前加上r或R表示该字符串是非转义的原始字符串。
2、在字符串前加上u或U表示该字符串是unicode字符串。