How can I use the readinto()
method call to an offset inside a bytearray
, in the same way that struct.unpack_from
works?
Asked
Active
Viewed 6,098 times
11

Matt Joiner
- 112,946
- 110
- 377
- 526
1 Answers
19
You can use a memoryview
to do the job. For example:
dest = bytearray(10) # all zero bytes
v = memoryview(dest)
ioObject.readinto(v[3:])
print(repr(dest))
Assuming that iObject.readinto(...)
reads the bytes 1, 2, 3, 4, and 5 then this code prints:
bytearray(b'\x00\x00\x00\x01\x02\x03\x04\x05\x00\x00')
You can also use the memoryview
object with struct.unpack_from
and struct.pack_into
. For example:
dest = bytearray(10) # all zero bytes
v = memoryview(dest)
struct.pack_into("2c", v[3:5], 0, b'\x07', b'\x08')
print(repr(dest))
This code prints
bytearray(b'\x00\x00\x00\x07\x08\x00\x00\x00\x00\x00')

srgerg
- 18,719
- 4
- 57
- 39
-
1My intention is to read directly into the bytearray at an offset, and avoid all the intermediate copying. – Matt Joiner Nov 25 '11 at 02:38
-
I've edited my answer to include an example using the `memoryview` class, which I think does what you want. – srgerg Nov 25 '11 at 02:53
-
1This memoryview form seems to accomplish what I wanted. If I did a similar thing with struct.unpack_into, and used a memoryview instead of an offset, would it be the same? If this is the case, please remove the rest of your answer to focus on this. – Matt Joiner Nov 25 '11 at 06:01
-
Thanks, I was checking whether I need to add this as an answer – Antti Haapala -- Слава Україні May 23 '16 at 05:08