python之pickle模块
2021-05-23 19:31
标签:进制 方法 one none 区别 floating api with open lists pickle模块实现了用于序列化和反序列化Python对象结构的二进制协议。 pickle协议和JSON之间有根本的区别。 使用pickle序列化数据并写入文件。 读取文件中的数据并使用pickle反序列化。 输出结果: 使用pickle序列化数据。 使用pickle反序列化数据。 输出结果: 使用dump()序列化数据。 使用load()反序列化数据。 输出结果: python之pickle模块 标签:进制 方法 one none 区别 floating api with open lists 原文地址:https://www.cnblogs.com/bad-robot/p/9734434.html1、pickle
1.1、简介
1.2、可以被pickle序列化的类型
1.3、与json的比较
2、方法
2.1、dump()
import pickle
def sayhi(name):
print("hello,",name)
info = {
‘name‘:‘alex‘,
‘age‘:22,
‘func‘:sayhi
}
f = open("pickle_test_2.text","wb")
pickle.dump(info,f) #f.write( pickle.dumps( info) )
f.close()
2.2、load()
import pickle
def sayhi(name):
print("hello2,",name)
f = open("pickle_test_2.text","rb")
data = pickle.load(f) #data = pickle.loads(f.read())
print(data)
print(data["func"]("Alex"))
{‘name‘: ‘alex‘, ‘age‘: 22, ‘func‘:
2.3、dumps()
import pickle
import json
def sayhi(name):
print("hello2,", name)
info = {
‘name‘:‘alex‘,
‘age‘:22,
‘func‘:sayhi
}
f = open("pickle_test_1.text" ,"wb")
# print(json.dumps(info))
f.write(pickle.dumps(info))
f.close()
2.4、loads()
import pickle
def sayhi(name):
print("hello2,",name)
f = open("pickle_test_1.text","rb")
data = pickle.loads(f.read())
print(data["func"]("Alex"))
hello2, Alex
None
3、实例
import pickle
# An arbitrary collection of objects supported by pickle.
data = {
‘a‘: [1, 2.0, 3, 4+6j],
‘b‘: ("character string", b"byte string"),
‘c‘: {None, True, False}
}
with open(‘data.pickle‘, ‘wb‘) as f:
# Pickle the ‘data‘ dictionary using the highest protocol available.
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
import pickle
with open(‘data.pickle‘, ‘rb‘) as f:
# The protocol version used is detected automatically, so we do not
# have to specify it.
data = pickle.load(f)
print(data)
{‘a‘: [1, 2.0, 3, (4+6j)], ‘b‘: (‘character string‘, b‘byte string‘), ‘c‘: {False, True, None}}