pickle
dump的结果是bytes, dump用的f文件句柄需要以wb的形式打开, load所用的f是'rb'模式
- 支持几乎所有对象的序列化
- 对于对象的序列化需要这个对象对应的类在内存中
- 对于多次dump / load的操作做了良好的处理
import pickle dic = {1: (12, 3, 4), ('a', 'b'): 4} pic_dic = pickle.dumps(dic) print(pic_dic) # bytes类型 new_dic = pickle.loads(pic_dic) print(new_dic)
结果:
b'x80x03}qx00(Kx01Kx0cKx03Kx04x87qx01Xx01x00x00x00aqx02Xx01x00x00x00bqx03x86qx04Kx04u.' {1: (12, 3, 4), ('a', 'b'): 4}
pickle支持几乎所有对象的
import pickle class Student: def __init__(self, name, age): self.name = name self.age = age zou = Student('aa', 22) ret = pickle.dumps(zou) pickle_data = pickle.loads(ret) print(pickle_data.name) print(pickle_data.age)
结果:
aa
22
例
import pickle class Student: def __init__(self, name, age): self.name = name self.age = age zou = Student('aaa', 83) with open('pickle_demo', 'wb') as f: pickle.dump(zou, f) with open('pickle_demo', 'rb') as f: pic = pickle.load(f) print(pic.name) # 没有上面的类就会报错,因为句话是从实例化类里拿name属性
结果:
aaa
例
import pickle with open('pickle_demo', 'wb') as f: pickle.dump({'k1': 'v1'}, f) pickle.dump({'k11': 'v1'}, f) pickle.dump({'k11': 'v1'}, f) pickle.dump({'k12': [1, 2, 3]}, f) pickle.dump(['k1', 'v1', 'l1'], f) with open('pickle_demo', 'rb') as f: while True: try: print(pickle.load(f)) except EOFError: break
结果:
{'k1': 'v1'} {'k11': 'v1'} {'k11': 'v1'} {'k12': [1, 2, 3]} ['k1', 'v1', 'l1']