I want to read specific part of the binary file. I will implement a binary file to "simulate" an array.
For example, assuming that all objects will have the same size (22 bytes hipotetically):
- Inserting an object at index 0 will occupate from 0-22 bytes of the file.
- Inserting an object at index 1 will occupate from 22-44 bytes of the file.
So, when I insert these two objects, i successfully read the second but I get error when trying to read the first one.
Imports
import pickle
from sys import getsizeof
Inserting first object
with open("test2", "wb") as f:
buffer = pickle.dumps(10)
print(getsizeof(buffer))
f.write(buffer)
f.close
Console:
22
So I insert another number in position 22 using seek()
with open("test2", "wb") as f:
buffer = pickle.dumps(20)
f.seek(22,1)
print(getsizeof(buffer))
f.write(buffer)
f.close
Console comproving sabe size
22
Now Trying to read the second number (number 20)
with open("test2", "rb") as f:
f.seek(22,1)
buffer = f.read()
print(getsizeof(buffer))
print(pickle.loads(buffer))
f.close
Console log successfuly showing the number and it's size in bytes
22 20
But now, when trying to read the first one:
with open("test2", "rb") as f:
buffer = f.read(22)
print(getsizeof(buffer))
print(pickle.loads(buffer))
f.close
Console show wrong requested byte size
39
And the error
Exception has occurred: _pickle.UnpicklingErrorload key, '\x00'.
I don't know if it's relevant, but this is all the file read
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x03K\x14.'