标签:进制 方法 one none 区别 floating api with open lists
pickle模块实现了用于序列化和反序列化Python对象结构的二进制协议。
pickle协议和JSON之间有根本的区别。
使用pickle序列化数据并写入文件。
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()
读取文件中的数据并使用pickle反序列化。
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‘: <function sayhi at 0x0000000005048510>} hello2, Alex None
使用pickle序列化数据。
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()
使用pickle反序列化数据。
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
使用dump()序列化数据。
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)
使用load()反序列化数据。
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}}
标签:进制 方法 one none 区别 floating api with open lists
原文地址:https://www.cnblogs.com/bad-robot/p/9734434.html