手记

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'}
0人推荐
随时随地看视频
慕课网APP