我有一个包含一些非 ASCII 字符的文件。
$ file bi companies.txt
text/plain; charset=utf-8
在我的 Python 3.4 桌面上,我可以打开这个文件没有问题:
>>> open('companies.txt').read()
'...'
在使用 Python 3.3 的 CI 系统上,我得到了这个:
>>> open('companies.txt').read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.3/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 1223: ordinal not in range(128)
但如果我明确指定 encoding='utf8',它会起作用:
>>> open('companies.txt', encoding='utf8').read()
'...'
在这两个系统上,sys.getdefaultencoding 返回 'utf-8'。
知道是什么导致系统行为不同吗?为什么 CI 系统尝试使用 ascii?
请您参考如下方法:
文本文件的编码由 locale.getpreferredencoding 决定, 而不是 sys.getdefaultencoding .
