dumps是将dict转化成str格式,loads是将str转化成dict格式。
1.创建a(创建字典并把字典里的内容存入另一个文档)
import pickleaccounts = { 1000:{ "name":"alex li", "email":"lijie@126.com", "passwd":"adc123", "balance":15000, "phone":13651054608, "bank_acc":{ "ICBC":2321434, "CBC":413432, "ABC":76568, } }, 1001: { "name": "chen li", "email": "wangxiao@126.com", "passwd": "adcewrf23", "balance": 15000, "phone": 13651054608, "bank_acc": { "ICBC": 23214434, "CBC": 4132432, "ABC": 7655668, } },}f = open("account.db","wb")#表示用写的模式打开文件,可以把每个输入的信息录入在文档里f.write(pickle.dumps(accounts))#dumps是将dict转化成str格式f.close()
2:创建b(修改余额并实时更新内容,此处需要把str内容转成dic的内容)
import pickleacc_file_name = "account.db"account_file = open(acc_file_name,"rb")#以读的形式打开account_dic = pickle.loads(account_file.read())#加载字典数据其中loads将str转化成dict格式account_file.close()account_dic[1000]["balance"] -=500f = open(acc_file_name,"wb")#把更新后的内容写进原文档里f.write(pickle.dumps(account_dic))f.close()print(account_dic)#扣完钱在写入文件
3;创建c
import picklef = open("account.db","rb")account_db = pickle.loads(f.read())#loads是将str转化成dict格式。print(account_db)
其中pickle模块与json大致相同