首页 > 解决方案 > 在二进制文件中读/写类对象?

问题描述

在我的 Python 项目中,我正在使用Forecast具有一些属性(温度、湿度等)的对象类。我想使用 2 个脚本,一个用于将数据写入二进制文件,一个用于读取它。

我都试过了 f = open(file,"wb")

f.write(object)

pickle.dump(object, open(file,"wb"))

但我的问题是用 pickle 编写类对象不会让我用 正确阅读它pickle.load,并且f.write不会让我这样做,因为“需要类似字节的对象”。

有人可以告诉我是否还有其他方法可以做到这一点?

标签: pythonclasspicklebinaryfilesread-write

解决方案


import pickle
with open('file','wb')as f:
         pickle.dump(object,f)
#the above argument is used to create a file using write byte 'wb'
with open('file','rb')as f:
         mp=pickle.load(f)
#the above argument is used to load the previous saved model into object 'mp'

如果有帮助,请告诉我;)


推荐阅读