pythonpython-bytearray

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.


Solution

  • 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])