标签:文件 模块 tuple abc with code 例子 value key
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‘\x80\x03(K{X\x06\x00\x00\x00abcdefq\x00]q\x01(X\x02\x00\x00\x00acq\x02K{e}q\x03(X\x03\x00\x00\x00keyq\x04X\x05\x00\x00\x00valueq\x05X\x04\x00\x00\x00key1q\x06X\x06\x00\x00\x00value1q\x07utq\x08.‘ 17 18 obj2 = pickle.loads(obj1) 19 print(type(obj2))# 输出:<class ‘tuple‘> 20 print(obj2) # 输出:(123, ‘abcdef‘, [‘ac‘, 123], {‘key‘: ‘value‘, ‘key1‘: ‘value1‘})
标签:文件 模块 tuple abc with code 例子 value key
原文地址:https://www.cnblogs.com/2018-1025/p/12169142.html