Python array.frombytes can't read byte object

Question:

This snipped thorws an error, I couldn’t find a solution so far.

from array import array
arr = array('B',[8, 3, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 2])
ab = arr.tobytes()
array.frombytes(ab)
TypeError                                 Traceback (most recent call last)
Cell In[117], line 4
      2 arr = array('B',[8, 3, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 2])
      3 ab = arr.tobytes()
----> 4 array.frombytes(ab)

TypeError: descriptor 'frombytes' for 'array.array' objects doesn't apply to a 'bytes' object

I treid this in Python 3.10.8 and a fresh 3.11.0 environment. No luck with neither

Asked By: linusrg

||

Answers:

You have to build another array before receive data frombytes:

from array import array
arr = array('B',[8, 3, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 2])
ab = arr.tobytes()

arr1 = array('B')
arr1.frombytes(ab)

Output:

>>> arr1
array('B', [8, 3, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 2])
Answered By: Corralien
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.