pickle
- pickle模块是将Python中所有的数据结构以及对象转换成bytes类型,然后还可一个反序列化还原回去
- Python语言识别的序列化模块,中国人作为第一交流语言,Python自带的,只有Python可用
- pickle支持Python所有的数据结构类型,能将所有的数据结构序列化成特殊的bytes,然后还可以反序列化还原,也是两对四个方法
1,用于网络传输
-
dumps ,loads
-
import pickle dic = {'k1':'v1','k2':'v2','k3':'v3'} str_dic = pickle.dumps(dic) print(str_dic) # bytes类型 dic2 = pickle.loads(str_dic) print(dic2) #字典
-
# 还可以序列化对象(函数()) import pickle def func(): print(666) ret = pickle.dumps(func) print(ret,type(ret)) # b'x80x03c__main__ func qx00.' <class 'bytes'> f1 = pickle.loads(ret) # f1得到 func函数的内存地址 f1() # 执行func函数
-
2,用于文件写读
-
dump ,load
-
dic = {(1,2):'oldboy',1:True,'set':{1,2,3}} f = open('pick序列化',mode='wb') pickle.dump(dic,f) f.close() with open('pick序列化',mode='wb') as f1: pickle.dump(dic,f1)
-
3,pickle序列化储存多个数据到一个文件夹中
-
import pickle lis = [1,2,3,4,5,6] with open('info','wb') as f: lis = pickle.dumps(lis) z = ' '.encode('utf-8') f.write(lis+z) f.write(lis+z) f.write(lis+z) # print(pickle.load(open("info",mode="rb"))) with open('info','rb') as f: for i in f: try: print(pickle.load(f)) except EOFError: break