2

我已经尝试过名为arraybit 的 Python 模块。它有一种将数组编码为字符串的方法。

>>>from array import array
>>>a=[1,2,3]
>>>a=array('B',a)
>>>print(a)
array('B',[1,2,3])
>>>print(a.tostring())
b'\x01\x02\x03'
>>>str(a.tostring())
"b'\x01\x02\x03'"

我想将.tostring()数组的版本保存到文件中,但open().write()只接受字符串。

有没有办法将此字符串解码为字节数组?

我想将它用于 OpenGL 数组(glBufferData接受字节数组)

提前致谢。

4

2 回答 2

2

无需进一步对数组进行编码/解码。您可以使用以下模式将返回的字节写入tostring()文件:'wb'

from array import array
a = array('B', [1, 2, 3])
with open(path, 'wb') as byte_file:
    byte_file.write(a.tostring())

您还可以使用以下'rb'模式从文件中读取字节:

with open(path, 'rb') as byte_file:
    a = array('B', byte_file.readline())

这将从文件中加载存储的数组并将其保存到变量中a

>>> print(a)
array('B', [1, 2, 3])
于 2015-08-10T13:09:52.623 回答
1

做这个:

>>> open('foo.txt','wb').write(a.tostring())
于 2015-08-10T13:08:47.213 回答