python_way ,json(自学)
python_way ,json
如果我们想将多行字典存放到文件中,并且还需要调出这些字典继续使用那么就要是用json。
首先将字典用json转换成字符串,存放到文件中。
a = {"tel": "", "user": "haha", "auth": "2", "is_lock": 3, "addr": "", "is_login": 0, "email": "", "passwd": 123}
with open('user_info.db',"a",encoding="utf-8") as w: #追加模式打开文件
outStr = json.dumps(a, ensure_ascii=False) + '\n' #将a字典转成字符串并+'\n'换行符
w.write(outStr) #存放到文件中
取出这些已经存放的字典
with open('user_info.db','r',encoding="utf-8") as r: #读模式打开文件 for line in r: #遍历每一行
print(line.type(line)) j = json.loads(line) #用json将每一行字符串转换成相应形状的类型 print(j,type(j))
{"tel": "", "user": "han", "auth": "2", "is_lock": 3, "addr": "", "is_login": 0, "email": "", "passwd": 123} <class 'str'>
{'is_login': 0, 'addr': '', 'user': 'han', 'is_lock': 3, 'auth': '2', 'tel': '', 'email': '', 'passwd': 123} <class 'dict'>