问题
在打开alice.txt时报错UnicodeDecodeError: 'gbk' codec can't decode byte 0x99 in position 1008: illegal multibyte sequence
,alice.txt甚至不是我写的,为什么作者的代码不会报错我的会呢?
代码
f_path = 'alice.txt'
try:
with open(f_path) as f_obj:
f_content = f_obj.read()
except FileNotFoundError:
msg = 'The file ' + f_path + ' does not exist.'
print(msg)
解决
txt是utf-8编码,所以编码需要转为utf-8。在打开文件时时添加encoding='utf-8'
:
f_path = 'alice.txt'
try:
with open(f_path, encoding='utf-8') as f_obj:
f_content = f_obj.read()
except FileNotFoundError:
msg = 'The file ' + f_path + ' does not exist.'
print(msg)