tengyue avatar

python 读文件报错

tengyue

Published: 17 Jan 2019 › Updated: 17 Jan 2019python 读文件报错

python 读文件报错

代码:

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())

Leave python 读文件报错 to:

Written by

Read more #python posts


Best Posts From tengyue

We have not curated any of tengyue's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From tengyue