我该如何解决这个错误? TypeError:'str'不支持缓冲区接口

时间:2013-02-19 17:27:28

标签: python string runtime-error

>>> import struct
>>> s = '\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
>>> struct.unpack('11B', s)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    struct.unpack('11B', s)
TypeError: 'str' does not support the buffer interface

这有什么问题?请帮忙。

1 个答案:

答案 0 :(得分:6)

在python 3上,struct.unpack()需要一个实现缓冲协议的对象,例如bytes值,而不是unicode str

>>> import struct
>>> s = b'\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
>>> struct.unpack('11B', s)
(0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0)

如果您正在从文件中读取此数据,请以二进制模式而不是文本模式打开文件以获取字节。