简体   繁体   中英

Python string contains byte array

I've experimented with the Python module named array a bit. It has got a way to encode arrays to strings.

>>>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'"

I want to save the .tostring() version of the array into a file, but the open().write() only accepts strings.

Is there a way to decode this string to a byte-array?

I want to use it for OpenGL arrays ( glBufferData accepts the byte-arrays)

Thanks in advance.

There's no need to encode/decode the array any further. You can write the bytes returned by tostring() into a file using the 'wb' mode:

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

You can also read bytes from a file using the 'rb' mode:

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

This will load the stored array from the file and save it into the variable a :

>>> print(a)
array('B', [1, 2, 3])

做这个:

>>> open('foo.txt','wb').write(a.tostring())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM