I have a npz file saved from numpy that I can load by using numpy.load(mynpzfile)
. However, I would like to save this file as a part of a binary file, packed with another file. Something like:
JavaScript
x
22
22
1
import numpy as np
2
from PIL import Image
3
from io import BytesIO
4
5
# Saving file jointly
6
input1 = open('animagefile.png', 'rb').read()
7
input2 = open('npzfile.npz', 'rb').read()
8
filesize = len(input1).to_bytes(4, 'big')
9
10
output = filesize + input1 + input2
11
12
with open('Output.bin', 'wb') as fp:
13
fp.write(output)
14
15
# Open them
16
input1 = open('Output.bin', 'rb').read()
17
filesize2 = int.from_bytes(input1[:4], "big")
18
19
segmentation = Image.open(BytesIO(input1[4:4+filesize2]))
20
# THIS LINE GIVES ME AN ERROR
21
layouts = np.frombuffer(input2[4+filesize2:])
22
However, when reading back the npz I get an error. I have tried load and frombuffer, and both give me an error:
- frombuffer:
ValueError: buffer size must be a multiple of element size
- load:
ValueError: embedded null byte
What can I do?
Advertisement
Answer
The last line should be input1
, not input2
. Also, guessing from the error message, you forgot to put BytesIO
.
JavaScript
1
3
1
layouts = np.load(BytesIO(input1[4+filesize2:]))
2
^^^^^^^ ^
3