python之pickle模塊
阿新 • • 發佈:2018-10-01
hello supported 復雜 包含 with open 2.4 反序 string import 1.3、與json的比較
1、pickle
1.1、簡介
pickle模塊實現了用於序列化和反序列化Python對象結構的二進制協議。
1.2、可以被pickle序列化的類型
- None, True, False
- intergers(整數), floating point numbers(浮點數), complex numbers(復數)
- strings, bytes, bytearrays
- 包含可pickle序列化的tuple, lists, sets, dictionaries
- 在模塊的頂層定義的函數(使用def定義,而不是lambda)
- 在模塊的頂層定義的內置函數
- 在模塊的頂層定義的類
1.3、與json的比較
pickle協議和JSON之間有根本的區別。
- JSON是一種文本序列化格式(它輸出unicode文本,盡管大多數時候它被編碼成utf-8),而pickle是二進制序列化格式;
- JSON是人可讀的,而pickle不是;
- JSON是可互操作的,並且在Python生態系統之外廣泛使用,而pickle則是特定於Python的;
- 在默認情況下,JSON只能表示Python內置類型的子集,並且沒有定制類;pickle可以代表大量的Python類型(其中許多是自動的,通過巧妙地使用Python的內省工具;復雜的情況可以通過實現特定的對象api來解決)
2、方法
2.1、dump()
使用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()
2.2、load()
讀取文件中的數據並使用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
2.3、dumps()
使用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()
2.4、loads()
使用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
3、實例
使用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}}
python之pickle模塊