【发布时间】:2023-11-29 11:57:01
【问题描述】:
我正在针对
执行这段代码Windows 上的 Python
'3.6.8 |Anaconda, Inc.| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]'
和
Linux 上的 Python
'3.6.6 (default, Mar 29 2019, 00:03:27) \n[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]'
代码使用wb 模式将一些字节写入文件,然后将其作为r 纯文本读取。我知道我应该按字节读取 (rb),但我很好奇为什么它在 Windows 上传递时会在 Linux 上中断?
import os
import tempfile
temp_dir = tempfile.mkdtemp()
temp_file = os.path.join(temp_dir, 'write_file')
expected_bytes = bytearray([123, 3, 255, 0, 100])
with open(temp_file, 'wb') as fh:
fh.write(expected_bytes)
with open(temp_file, 'r', newline='') as fh:
actual = fh.read()
在 Linux 上引发异常:
Traceback (most recent call last):
File "<input>", line 11, in <module>
File "/home/.../lib64/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid start byte
获取默认系统编码(使用sys.getdefaultencoding())显示
'utf-8' 在两台机器上。
【问题讨论】:
-
可能是因为在 Windows 系统上读取时使用的默认编码不是 utf-8,而是像 latin-1 这样的编码,其中所有字节都对应一个有效字符。
-
嗯,我刚刚检查了
sys.getdefaultencoding(),两台机器上都是utf-8... -
来自
open的文档:'默认编码取决于平台(无论 locale.getpreferredencoding() 返回什么)' - 这个返回什么? -
试试
locale.getpreferredencoding() -
还有:sys.getdefaultencoding() :返回 Unicode 实现使用的当前默认字符串编码的名称。
标签: python arrays python-3.x file binary