python专用
没什么限制
能处理很多数据类型!
dump 需要的文件f句柄 需要wb形式打开,load需要rb模式
支持对象序列化!需要这个对象对应的类在内存中
转成bytes类型!也是序列类型
dic = {1:(12,3,4),('a','b'):4} import pickle pic_dic = pickle.dumps(dic) print(pic_dic) # bytes类型 b'x80x04x95x1bx00x00x00x.... new_dic = pickle.loads(pic_dic) print(new_dic) # {1: (12, 3, 4), ('a', 'b'): 4}
支持几乎所有对象的
class Student: def __init__(self,name,age): self.name = name self.age = age alex = Student('alex',83) ret = pickle.dumps(alex) 小花 = pickle.loads(ret) print(小花.name) print(小花.age)
class Student: def __init__(self,name,age): self.name = name self.age = age alex = Student('alex',83) with open('pickle_demo','wb') as f: pickle.dump(alex,f) with open('pickle_demo','rb') as f: 旺财 = pickle.load(f) print(旺财.name)
这种方式可以重复写入,然后重复拿出来(这里有一个异常,在最后一次没有值,会报错,这里用了异常处理)
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