Python: Transferring two byte variables with a binary file

帅比萌擦擦* 提交于 2020-03-25 05:51:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!