标签:form edits ict open 读取 type class str dump
对Python对象进行序列化,便于存储和传输
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'}
pickle.dump(obj, file)
可以存储多个对象,读取时按存储顺序读取
>>> import pickle
>>> mydict = {'id':123, 'name':'abc'}
>>> file = open('pickle.txt','wb')
>>> pickle.dump(mydict, file)
>>> file.close()
pickle.load(obj, file)
>>> import pickle
>>> file = open('pickle.txt','rb')
>>> newdict = pickle.load(file)
>>> file.close()
>>> newdict
{'id': 123, 'name': 'abc'}
想进一步了解编程开发相关知识,与我一同成长进步,请关注我的公众号“松果仓库”,共同分享宅&程序员的各类资源,谢谢!!!
标签:form edits ict open 读取 type class str dump
原文地址:https://www.cnblogs.com/songshudadi/p/11910869.html