Python:使用二进制文件传输两个字节变量 [英] Python: Transferring two byte variables with a binary file

查看:162
本文介绍了Python:使用二进制文件传输两个字节变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个字节数组,

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)

此代码将创建一个包含两个字节数组的.bin文件

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.

谢谢

推荐答案

Pythons pickle 用于存储和检索对象。

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)

您可以从其他问题中找到更多详细信息如何在python中保存和恢复多个变量?

You can find more details from other question How do I save and restore multiple variables in python?

这篇关于Python:使用二进制文件传输两个字节变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆