【问题标题】:Implications of reading `byte` vs. `bytearray` from file in python在 python 中从文件中读取 `byte` 与 `bytearray` 的含义
【发布时间】:2013-03-14 04:20:11
【问题描述】:

如果我使用ord()chr() 从文件中读取bytes,我经常会出错。可能是什么原因?

【问题讨论】:

  • ord 给出字符串的序号。在 3.x 中,将其用于 bytes 是毫无意义的。当您对 bytes 进行索引或迭代时,您将获得 0-255 范围内的整数,例如b'a'[0] == 97list(b'\x01\x02\x03') == [1, 2, 3].

标签: file python-3.x bytearray byte


【解决方案1】:

如果你从文件中读取一个byte,它将被表示为一个字节字符(你应该使用ord()):

>>> print(index_file.read(1))
b'\x0a'

如果你读取一个字节数组,即bytearray,数组的每个成员都是简单的int(你应该使用chr()):

>>> print(index_file.read(2)[0])
10

【讨论】:

  • 在上述两种情况下,您都读取了 bytes 对象。 bytearray 是一个 mutable 类型,在其他方面类似于 immutable bytes。对于这两种类型,索引/迭代都会返回 0-255 范围内的整数。
猜你喜欢
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多