python用pickle模块实现“增删改查”的简易功能
pickle的作用:
1:pickle.dump(dict,file)把字典转为二进制存入文件.
2:pickle.load(file)把文件二进制内容转为字典
importpickle
#增
defadds():
users={"name":"yangbin","age":22,"sex":"male"}
withopen("red.txt","wb")asf:
pickle.dump(users,f)
dic={}
withopen("red.txt")assd:
dic=pickle.load(sd)
printdic
#删
defdeletes():
dic={}
withopen("red.txt")asf:
dic=pickle.load(f)
dic.pop("sex")
withopen("red.txt","wb")asff:
pickle.dump(dic,ff)
printdic
#改
defchanges():
dic={}
withopen("red.txt")asf:
dic=pickle.load(f)
dic["age"]=28
withopen("red.txt","wb")asf:
pickle.dump(dic,f)
printdic
#查
deffinds():
dic={}
withopen("red.txt")asf:
dic=pickle.load(f)
fork,vindic.items():
print"%s--->%s"%(k,v)
adds()
deletes()
changes()
finds()
运行结果:
root@python3:/python/python2/linshi#python01.py
{'age':22,'name':'yangbin','sex':'male'}
{'age':22,'name':'yangbin'}
{'age':28,'name':'yangbin'}
age--->28
name--->yangbin
root@python3:/python/python2/linshi#
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。