UnicodeDecodeError: 'gbk' codec can't decode byte 0xb1 in position 94: illegal multibyte sequence
有时候用open()方法打开文件读取文件的时候会出现这个问题:‘GBK’编×××无法解码94号位置的字节0xb1:非法多字节序列。错误信息提示了使用“GBK”解码。
1.分析
pycharm自动使用的是‘UTF-8’编码,好像没有什么问题,为什么会出现这个错误呢。结果查了下open()函数的注解,里面又这么一段话:
encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. *The default encoding is platform dependent*, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings.
The default encoding is platform dependent:默认编码方式取决于平台。这也就不奇怪会用‘GBK’编码了,平台不一样,编码方式不一样,所以读取的时候回出现错误。
2.解决方法
# 1.以byte读取,并以‘utf-8’解码
# fp = open(filename, 'rb')
# content = fp.read()
# self.content = content.decode('utf-8')
# fp.close()
# 2.在打开文件时指定编码方式
fp = open(filename, encoding='utf-8')
content = fp.read()
self.content = content
fp.close()
如有不同见解,欢迎分享。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有