问题
Let's say I have two bytearray,
b = bytearray(b'aaaaaa')
b1 = bytearray(b'bbbbbb')
file_out = open('bytes.bin', 'ab')
file_out.write(b)
file_out.write(b1)
this code will create a .bin file which contains two bytearrays
how to read this file and store those two variables also decode them back to string?
my goal is to transfer these bytes for other programs to read by making a file. I'm not sure if this bytearray + appending is a good idea.
Thanks
回答1:
Pythons pickle is meant for storing and retrieving objects.
It will take care of encoding and decoding of the contents.
You can use it in your case like following,
import pickle
b = bytearray(b'aaaaaa')
b1 = bytearray(b'bbbbbb')
# Saving the objects:
with open('objs.pkl', 'wb') as f:
pickle.dump([b, b1], f)
# Getting back the objects:
with open('objs.pkl') as f:
b, b1 = pickle.load(f)
You can find more details from other question How do I save and restore multiple variables in python?
来源:https://stackoverflow.com/questions/60795901/python-transferring-two-byte-variables-with-a-binary-file