If I have a binary file, I can open it in mode rb and move the pointer with .seek():
with open(fname, "rb") as fid:
fid.seek(101)
But this is not possible with a bytearray:bytearray(10).seek(1).
Does a bytearray which supports seek exist?
I have 2 almost identical code snippets reading data from a binary file/buffer that I would like to merge, one reading from a binary file and one from a byte array. The reading operation is done with numpy, with either numpy.fromfile or numpy.frombuffer. Both accept an argument offset to control the pointer position, but in a slightly different manner. fromfile defines the offset from the current position while frombuffer defines the offset from the beginning of the buffer.
Any idea on which object I could use instead of bytearray to be able to run the same reader code snippet on either an opened binary file fid or on a bytearray-like buffer?
I think the easiest thing to do there is to subclass bytearray, and just add the
seek,tell,readandwritemethods - it will work just like a bytearray for everything else, and can be used most places file-like objects are expected:And, using this in the interactive mode: