2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Uncle Dino
  • 812
  • 1
  • 7
  • 23

2 Answers2

2

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])
Markus Meskanen
  • 19,939
  • 18
  • 80
  • 119
1

Do this:

>>> open('foo.txt','wb').write(a.tostring())
noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67