我在使用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..