首页 > 代码库 > pickle模块

pickle模块

1.

import pickle
accounts = {
    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))
f.close()

 2:

import pickle

acc_file_name = "account.db"

account_file = open(acc_file_name,"rb")
account_dic = pickle.loads(account_file.read())#加载字典数据
account_file.close()
account_dic[1000]["balance"] -=500
f = open(acc_file_name,"wb")
f.write(pickle.dumps(account_dic))
f.close()
print(account_dic)

#扣完钱在写入文件

3:

import pickle
f = open("account.db","rb")
account_db = pickle.loads(f.read())
print(account_db)

 其中pickle模块与json大致相同

pickle模块