代码:
with open('C:\Users\tengy\Desktop\aaa.txt') as f:
print(f.read())
问题1、运行一段python代码,读取一个文件报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 205: illegal multibyte sequence
解决:
with open('C:\Users\tengy\Desktop\aaa.txt', encoding='UTF-8') as f:
问题2、SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
解决:
由于我用的windows系统,所以路径中的斜杠需要转义:
with open('C:\\Users\\tengy\\Desktop\\aaa.txt',encoding='UTF-8') as f:
print(f.read())