问题描述:
python里使用with函数打开文件,文件里有中文字符时,报错:
‘gbk’ codec can’t decode byte 0x80 in position 9: illegal multibyte sequence
代码写法如下:
with open('..\test.txt') as a:
报错如下:
解决办法:
第一种:加 ‘r’, encoding='utf-8
代码写法如下:
with open('..\test.txt', 'r', encoding='utf-8') as a:
第二种:加 ‘rb’
注意:如果写成此格式,再使用startswith函数会报错:
TypeError: startswith first arg must be bytes or a tuple of bytes, not str
代码写法如下:
with open('..\test.txt', 'rb') as a:
报错如下: