python - 以读取模式 Python 3 读取二进制文件 - 在 Windows 上通过,在 Linux 上失败

标签 python arrays python-3.x file binary

我正在执行这段代码

Windows 上的 Python

'3.6.8 |Anaconda, Inc.| (默认,2019 年 2 月 21 日 18:30:04)[MSC v.1916 64 位 (AMD64)]'

Linux 上的 Python

'3.6.6(默认,2019 年 3 月 29 日,00:03:27)\n[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]'

该代码使用 wb 模式将一些字节写入文件,然后将其作为 r 纯文本读取。我知道我应该读取字节 (rb),但我很好奇为什么它会在 Linux 上中断而在 Windows 上传递?

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'

最佳答案

当以文本模式打开文件时,使用'rt'(其中'r'和't'都是默认值),您从文件中读取的所有内容都会即时透明地解码并作为 str 对象返回,如 Text I/O 中所述。 .

您可以在打开文件时强制使用编码,例如:

f = open("myfile.txt", "r", encoding="utf-8")

open 的文档中所述:

The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

(请注意,sys.getdefaultencoding() 是不相关的:它返回 Unicode 实现使用的当前默认字符串编码的名称)

正如您在评论中所述,在您的系统上,locale.getpreferredencoding() 在 Windows 上提供“cp1252”,在 Linux 上提供“UTF-8”。

CP-1252是单字节编码,其中每个字节对应一个字符。因此,无论您读取什么文件,它包含的数据都可以转换为字符串。

UTF-8但是,使用可变宽度编码,其中并非所有字节序列都有效并表示字符。这就是为什么当某些字节无法解码时尝试在 Linux 系统上读取文件会失败。

关于python - 以读取模式 Python 3 读取二进制文件 - 在 Windows 上通过,在 Linux 上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55534642/

相关文章:

PHP重构数组Paypal TransactionSearch函数

arrays - bash 数组保留包含字符串的元素

python - 从 Scrapy 将超过 1 个项目存储到 Mysql 时出现问题

python - 写入打开的 CSV 时跳过 header

c - 当我只能定义一个可变长度数组时,为什么要使用 malloc()?

python - PDF 创建和在其中写入内容 - PyPDF2

python - 为什么start_transaction不设置事务隔离级别?

python - 如何通过管道将子进程调用传递给文本文件?

python - 深度实验室 : InvalidArgumentError: NodeDef mentions attr 'dilations' not in Op<name=Conv2D;

python - 如何使用 NumPy 数组算术 Python 对有限差分法进行矢量化?