python - 在二进制文件中读/写类对象?
问题描述
在我的 Python 项目中,我正在使用Forecast
具有一些属性(温度、湿度等)的对象类。我想使用 2 个脚本,一个用于将数据写入二进制文件,一个用于读取它。
我都试过了
f = open(file,"wb")
f.write(object)
和
pickle.dump(object, open(file,"wb"))
但我的问题是用 pickle 编写类对象不会让我用 正确阅读它pickle.load
,并且f.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'
如果有帮助,请告诉我;)
推荐阅读
- swift - 如何快速使用 char *c = "\x0D\x0A"
- python - matplotlib中的逗号是什么意思?- Python
- javascript - NodeJS 等待优先级 - 一个等待以错误的顺序在另一个之前运行(Express、SQLite3 db.all 和 db.run)
- zurb-foundation - JOINTSWP 如何在 JOINTWSP 中开启基础原型断点
- python-3.x - 如何将此 24615478158188 uid 代码转换为来自 ESP-RFID 的 f69a4e9e uid 代码?
- bash - Bash脚本将管道sed的输出保存到变量
- express - Express Handlebars - 向不同页面添加独特的样式表和脚本
- c# - 将 HashSet 列表高效转换为单个 HashSet
- reactjs - 有谁知道如何在 React Native 中制作这样的布局?
- regex - 使用 str_match_all 匹配 R 中字符的开头和结尾