UnicodeDecodeError: 'gbk' codec can't decode byte 0xa7 in position 1425: illegal multibyte sequence

本文探讨了Python中使用open函数时遇到的文件编码问题,并提供了解决方案。当默认编码与文件实际编码不符时,作者建议显式指定encoding参数为'utf-8'。由于无法全局更改默认编码,文章还讨论了其他可能的解决策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在使用python导出chrome的bookmarks时,报了这个错误。查到原因是文件的内容与写入目标文件的编码问题不统一的问题。可以在open和write时都显示设置encoding=’utf-8’。但这种方式用起来感觉很不方便,想找到一劳永逸的方法,设置Open,write的默认编码为utf-8。

查看open源码:

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open

"""
In text mode, if encoding is not specified the encoding used is platform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding
"""

也即如果没有申明encoding,会默认调用locale.getpreferredencoding(False)方法,这个方法返回当前系统的默认编码,非当前IDEA环境编码等。而这个系统编码windows是不允许修改的,也即我们没有办法手动修改locale.getpreferredencoding(False)的结果。那有python有什么办法设置默认的open编码呢?

查看了官方的文档 https://www.python.org/dev/peps/pep-0540/#locale-encoding-and-utf-8,其中有一段关于open的编码问题,如下:

On the flip side, Python 3.6 is already using UTF-8 by default on macOS, Android and Windows (PEP 529) for most functions – although open() is a notable exception here. UTF-8 is also the default encoding of Python scripts, XML and JSON file formats. The Go programming language uses UTF-8 for all strings.

谷歌翻译如下 :

另一方面,Python 3.6已经在macOS,Android和Windows(PEP 529)上默认使用UTF-8来处理大多数函数 - 虽然open()在这里是一个值得注意的例外。 UTF-8也是Python脚本,XML和JSON文件格式的默认编码。 Go编程语言对所有字符串使用UTF-8。

也即python实现了很多默认编码为utf-8,但Open是个例外,只能说一句MDZZ..

一劳永逸的办法是没有了,那只能退而求其次去找其他办法了,要么统一下open的编码,或者自己再封装下open或在先执行py时重新封装下locale.getpreferredencoding()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值