#序列化:将原来的字典、列表等内容转化为一个字符串数据类型 #为什么需要序列化呢? # 数据存储 #网络传输(bytes传输) #序列化: 数据类型(元组、列表等)----> 字符串的过程 # 反序列化: 字符串 ----> 数据类型(元组、列表等)的过程 #json ***** #pickle **** #shelve *** #json # 通用的序列化格式 #只有很少的一部分数据类型能够通过json转化成字符串 #pickle #所有的python中的数据类型都可以转换成字符串形式 #pickle序列化的内容只有python能理解 #反序列化依赖python代码 #shelve #序列化句柄 #使用句柄直接操作,非常方便 #json (dumps:序列化方法 loads反序列化 ) 在内存中操作 #数字 字符串 列表 字典 可以通过json序列化 # dic ={"k1":"v1","k2":2} # print(type(dic),dic) #<class 'dict'> {'k1': 'v1', 'k2': 2} 字典、列表等是单引号 # import json # str_d = json.dumps(dic) # print(type(str_d),str_d) #<class 'str'> {"k1": "v1", "k2": 2} 通过json转化为str是双引号 # dic_d = json.loads(str_d) # print(type(dic_d),dic_d) #<class 'dict'> {'k1': 'v1', 'k2': 2} #一次性写和读 #json (dump load) 和打开文件有关,先序列化在写入文件 # import json # dic ={'k1':'v1','k2':2} # with open('xuli',mode='w',encoding='utf-8') as f: # json.dump(dic,f) #xuli文件内容为{"k1": "v1", "k2": 2} # with open('xuli',mode='r',encoding='utf-8') as f: # res = json.load(f) # print(type(res),res) #<class 'dict'> {'k1': 'v1', 'k2': 2} # import json # dic = ['中国',1,'a',2] # # with open('xuli',mode='w',encoding='utf-8') as f: # # # json.dump(dic,f) #["u4e2du56fd", 1, "a", 2] # # json.dump(dic,f,ensure_ascii=False) #["中国", 1, "a", 2] # with open('xuli',encoding='utf-8') as f: # res = json.load(f) # print(type(res),res) #<class 'list'> ['中国', 1, 'a', 2] #多次写和读(多次读写只能用dumps和loads dump和load只能一次性读写) import json # l = [{'k1':'111'},{'k2':'111'},{'k3':'111'}] # with open('file',mode='w') as f: # for dic in l: # str_dict = json.dumps(dic) # f.write(str_dict+' ') # with open('file',mode='r+') as f: # l = [] # for line in f: # dic = json.loads(line.strip()) # print(dic) # l.append(dic) # print(l)
# pickle dumps loads dump load import pickle # dic = {'k1':'v1','k2':'v2','k3':'v3 '} # str_dic = pickle.dumps(dic) # print(str_dic) #b'x80x03}qx00(Xx02x00x00x00k1qx01Xx02x00x00x00v1qx0 # #pickle dumps出来是bytes类型 # dic2 = pickle.loads(str_dic) # print(dic2) #pickle 可以一次dump也可以多次dump # import time # strut_time = time.localtime(900000000) # print(strut_time) # with open('file',mode='wb') as f: # pickle.dump(strut_time,f) # # with open('file',mode='rb') as f: # strut2_time =pickle.load(f) # print(strut2_time.tm_year)