1.pickle序列介绍:提供4个关键字:dumps,dump,loads,load
语法:f.write(pickle.dumps(dict))=pickle.dump(dict,f)
"r=pickle.loads(f.read())" = "r=pickle.load(f)
将字典存入文件,由于字典格式不能转化成字节格式的,所以引入pickle
A.将一个字典转化成pickle序列存入一个文件
import pickle #import cPickle as pickle
accounts={ 1000:{ 'name':'Tom', 'email':'22016311@qq.com', 'passwd':'abc123', 'balance':20000, 'phone':'44165465', 'bank_acc':{ 'ICBC':165116161, 'CBC':16516516516, 'ABC':656151616516 } }, 1001:{ 'name':'Tom1', 'email':'220116311@qq.com', 'passwd':'abc1123', 'balance':210000, 'phone':'441654165', 'bank_acc':{ 'ICBC':16511161611, 'CBC':165165165161, 'ABC':6561516165161 } } }
print (pickle.dumps(accounts)) #将字典转成pickle序列 f=open("account.db","wb") #写入文件account.db f.write(pickle.dumps(accounts)) #写入文件account.db #pickle.dump(accounts,f)
f.close() ------------------------------------------------------------------- b'\x80\x03}q\x00(M\xe8\x03}q\x01(X\x04\x00\x00\x00nameq\x02X\x03\x00\x00\x00Tomq\x03X\x05\x00\x00\x00emailq\x04X\x0f\x00\x00\x0022016311@qq.comq\x05X\x06\x00\x00\x00passwdq\x06X\x06\x00\x00\x00abc123q\x07X\x07\x00\x00\x00balanceq\x08M NX\x05\x00\x00\x00phoneq\tX\x08\x00\x00\x0044165465q\nX\x08\x00\x00\x00bank_accq\x0b}q\x0c(X\x04\x00\x00\x00ICBCq\rJ\x01y\xd7\tX\x03\x00\x00\x00CBCq\x0e\x8a\x05\xa4\nv\xd8\x03X\x03\x00\x00\x00ABCq\x0f\x8a\x06\x04\x1c\xaf\xc5\x98\x00uuM\xe9\x03}q\x10(h\x02X\x04\x00\x00\x00Tom1q\x11h\x04X\x10\x00\x00\x00220116311@qq.comq\x12h\x06X\x07\x00\x00\x00abc1123q\x13h\x08JP4\x03\x00h\tX\t\x00\x00\x00441654165q\x14h\x0b}q\x15(h\r\x8a\x05\x0bU$\xd8\x03h\x0e\x8a\x05ij\x9ct&h\x0f\x8a\x06)\x18\xd7\xb8\xf7\x05uuu.'
|
B.重新创建一个新的python文件读取account.db中的内容:
import pickle
account_file=open("account.db","rb") #打开文件 account_dict=pickle.loads(account_file.read()) #以pickle加载文件 #account_dict=pickle.load(account_file) #print (account_dict) account_file.close() #print(type(account_dict[1000]['balance'])) account_dict[1000]['balance'] -= 500 #取字典中balance然后减500 print (account_dict)
f=open("account.db","wb") f.write(pickle.dumps(account_dict)) #将变更后的内容dumps入文件 f.close() print (account_dict) -----------------------------------------------------------------------------
{1000: {'name': 'Tom', 'email': '22016311@qq.com', 'passwd': 'abc123', 'balance': 19500, 'phone': '44165465', 'bank_acc': {'ICBC': 165116161, 'CBC': 16516516516, 'ABC': 656151616516}}, 1001: {'name': 'Tom1', 'email': '220116311@qq.com', 'passwd': 'abc1123', 'balance': 210000, 'phone': '441654165', 'bank_acc': {'ICBC': 16511161611, 'CBC': 165165165161, 'ABC': 6561516165161}}} {1000: {'name': 'Tom', 'email': '22016311@qq.com', 'passwd': 'abc123', 'balance': 19500, 'phone': '44165465', 'bank_acc': {'ICBC': 165116161, 'CBC': 16516516516, 'ABC': 656151616516}}, 1001: {'name': 'Tom1', 'email': '220116311@qq.com', 'passwd': 'abc1123', 'balance': 210000, 'phone': '441654165', 'bank_acc': {'ICBC': 16511161611, 'CBC': 165165165161, 'ABC': 6561516165161}}}
|