Python pickle模块实现对象序列化
作者:松鼠大帝 时间:2022-03-04 03:51:22
这篇文章主要介绍了Python pickle模块实现对象序列化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
作用
对Python对象进行序列化,便于存储和传输
Python对象序列化成bytes类型
pickle.dumps(obj) 将Python对象转化为bytes类型
pickle.loads(str) 将转化成的bytes类型数据还原成对象
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import pickle
>>> mydict = {'id':123, 'name':'abc'}
>>> pickle_str = pickle.dumps(mydict)
>>> pickle_str
b'\x80\x03}q\x00(X\x02\x00\x00\x00idq\x01K{X\x04\x00\x00\x00nameq\x02X\x03\x00\x00\x00abcq\x03u.'
>>> newdict = pickle.loads(pickle_str)
>>> newdict
{'id': 123, 'name': 'abc'}
Python对象序列化写入文件
pickle.dump(obj, file)
可以存储多个对象,读取时按存储顺序读取
>>> import pickle
>>> mydict = {'id':123, 'name':'abc'}
>>> file = open('pickle.txt','wb')
>>> pickle.dump(mydict, file)
>>> file.close()
从文件反序列化读取Python对象
pickle.load(obj, file)
>>> import pickle
>>> file = open('pickle.txt','rb')
>>> newdict = pickle.load(file)
>>> file.close()
>>> newdict
{'id': 123, 'name': 'abc'}
来源:https://www.cnblogs.com/songshudadi/p/11910869.html
标签:python,pickle,模块,序列,化
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解django+django-celery+celery的整合实战
2022-11-14 12:25:13
![](https://img.aspxhome.com/file/2023/9/87989_0s.png)
python中模块导入模式详解
2022-04-03 08:54:29
![](https://img.aspxhome.com/file/2023/4/109474_0s.png)
如何用ASP获知机器的网络配置?
2010-06-11 19:58:00
NumPy索引与切片的用法示例总结
2022-05-13 19:33:38
![](https://img.aspxhome.com/file/2023/4/80544_0s.png)
高考要来啦!用Python爬取历年高考数据并分析
2021-06-10 04:08:25
![](https://img.aspxhome.com/file/2023/9/68439_0s.jpg)
简单文件操作python 修改文件指定行的方法
2022-07-13 15:02:52
IE中jscript/javascript的条件编译
2007-10-03 14:03:00
如何把图片上传到数据库中并显示出来?
2009-11-06 13:50:00
使用Pyparsing处理复杂文本实现过程
2023-03-21 13:37:44
基于python的Tkinter编写登陆注册界面
2022-12-20 09:44:30
基于Python-Pycharm实现的猴子摘桃小游戏(源代码)
2023-07-07 06:31:22
![](https://img.aspxhome.com/file/2023/5/60705_0s.png)
大家都说好用的Python命令行库click的使用
2023-05-17 04:00:15
使用python编写简单计算器
2023-08-27 17:07:46
![](https://img.aspxhome.com/file/2023/6/70646_0s.jpg)
Python词法结构
2022-01-10 00:33:21
VBScript运行出错信息涵义列表
2007-08-12 18:03:00
对python中数组的del,remove,pop区别详解
2021-01-23 09:22:31
python基本数据类型练习题
2022-07-21 14:26:26
![](https://img.aspxhome.com/file/2023/6/98996_0s.png)
Django serializer优化类视图的实现示例
2021-11-23 23:16:46
![](https://img.aspxhome.com/file/2023/2/86402_0s.png)
用sleep间隔进行python反爬虫的实例讲解
2023-02-10 07:00:42
![](https://img.aspxhome.com/file/2023/1/103781_0s.png)
Python Flask-web表单使用详解
2022-07-14 01:55:59
![](https://img.aspxhome.com/file/2023/7/90747_0s.jpg)