pickle模块
例子
1 import pickle
2
3 obj = 123, "abcdef", ["ac", 123], {"key": "value", "key1": "value1"}
4 print(obj)
5
6 # 序列化到文件
7 with open(r"data1.pk", "wb") as f:
8 pickle.dump(obj, f)
9
10 with open(r"data1.pk", "rb") as f:
11 print(pickle.load(f))# 输出:(123, 'abcdef', ['ac', 123], {'key': 'value', 'key1': 'value1'})
12
13 # 序列化到内存(字符串格式保存),然后对象可以以任何方式处理如通过网络传输
14 obj1 = pickle.dumps(obj)
15 print(type(obj1))# 输出<class 'bytes'>
16 print(obj1)# 输出:python专用的存储格式 b'x80x03(K{Xx06x00x00x00abcdefqx00]qx01(Xx02x00x00x00acqx02K{e}qx03(Xx03x00x00x00keyqx04Xx05x00x00x00valueqx05Xx04x00x00x00key1qx06Xx06x00x00x00value1qx07utqx08.'
17
18 obj2 = pickle.loads(obj1)
19 print(type(obj2))# 输出:<class 'tuple'>
20 print(obj2) # 输出:(123, 'abcdef', ['ac', 123], {'key': 'value', 'key1': 'value1'})