一、json格式的限制
1.json格式的key必须是字符串数据类型,如果是数字dumps后会被转为字符串。
# dic = {1:2,3:4} # str_dic = json.dumps(dic) # print(str_dic) # new_dic = json.loads(str_dic) # print(new_dic)
2.元组可以作为vaule但会被转为列表,并且不能作为key
3.可以多次将数据dump进文件,但不能load出来。
# dic = {'abc':(1,2,3)} # lst = ['aaa',123,'bbb',12.456] # with open('json_demo','w') as f: # json.dump(lst,f) # json.dump(dic,f) # with open('json_demo') as f: # ret = json.load(f) # print(ret)
#报错
4.想多次dump并load出来
dic = {'abc':(1,2,3)} lst = ['aaa',123,'bbb',12.456] with open('json_demo','w') as f: str_lst = json.dumps(lst) str_dic = json.dumps(dic) f.write(str_lst+' ') f.write(str_dic+' ') with open('json_demo') as f: for line in f: ret = json.loads(line) print(ret)
二、pickl
1.dump的结果是bytes,dump用的f文件句柄需要以wb的形式打开,load所用的f是'rb'模式
2.pickle支持几乎所有对象的
把对象写入,及读出
# 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)
三、hashlib
1.
# 能够把 一个 字符串 数据类型的变量
# 转换成一个 定长的 密文的 字符串,字符串里的每一个字符都是一个十六进制数字
背下来
# md5_obj = hashlib.md5()#或者sha1等 # md5_obj.update(s1.encode('utf-8'))#encode必须要 # res = md5_obj.hexdigest() # print(res,len(res),type(res))
2.动态加盐,更加安全
# username = input('username : ') # passwd = input('password : ') # md5obj = hashlib.md5(username.encode('utf-8')) # md5obj.update(passwd.encode('utf-8')) # print(md5obj.hexdigest())
3.文件一致性检验
# md5_obj = hashlib.md5() # with open('5.序列化模块_shelve.py','rb') as f: # md5_obj.update(f.read()) # ret1 = md5_obj.hexdigest() # # md5_obj = hashlib.md5() # with open('5.序列化模块_shelve.py.bak','rb') as f: # md5_obj.update(f.read()) # ret2 = md5_obj.hexdigest() # print(ret1,ret2)