使用pickle存储数据dump 和 load实例讲解
使用pickle模块来dump你的数据:对上篇博客里的sketch.txt文件:
importos
importsys
importpickle
man=[]
other=[]
try:
data=open('sketch.txt')
foreach_lineindata:
try:
(role,line_spoken)=each_line.split(':',1)
line_spoken=line_spoken.strip()
ifrole=='Man':
man.append(line_spoken)
elifrole=='OtherMan':
other.append(line_spoken)
exceptValueError:
pass
data.close()
exceptIOError:
nester.print_lol('Thedatafileismissing!')
try:
withopen('man_data.txt','wb')asman_file:
pickle.dump(man,man_file)
withopen('other_data.txt','wb')asother_file:
pickle.dump(other,other_file)
exceptIOErroraserr:
print('Fileerror:'+str(err))
exceptpickle.PickleErrorasperr:
print('Picklingerror:'+str(perr))
打开man_data.txt,看结果:
]q(X'Isthistherightroomforanargument?qXNoyouhaven't!qXWhen?qXNoyoudidn't!qXYoudidn't!qXYoudidnot!qX=Ah!(takingouthiswalletandpaying)Justthefiveminutes.qXYoumostcertainlydidnot!qXOhnoyoudidn't!qXOhnoyoudidn't!q XOhlook,thisisn'tanargument!qXNoitisn't!qXIt'sjustcontradiction!q XItIS!qXYoujustcontradictedme!qXYouDID!qXYoudidjustthen!qX"(exasperated)Oh,thisisfutile!!qX Yesitis!qe.
把已存储在man_data.txt上的二进制文件,恢复成可以读的文件,存放在new_man.txt中:
importnester
importos
importsys
importpickle
man=[]
other=[]
new_man=[]
try:
data=open('sketch.txt')
foreach_lineindata:
try:
(role,line_spoken)=each_line.split(':',1)
line_spoken=line_spoken.strip()
ifrole=='Man':
man.append(line_spoken)
elifrole=='OtherMan':
other.append(line_spoken)
exceptValueError:
pass
data.close()
exceptIOError:
print_lol('Thedatafileismissing!')
try:
#withopen('man_data.txt','wb')asman_file:
#pickle.dump(man,man_file)
#withopen('other_data.txt','wb')asother_file:
#pickle.dump(other,other_file)
withopen('man_data.txt','rb')asman_file:
new_man=pickle.load(man_file)
exceptIOErroraserr:
print('Fileerror:'+str(err))
exceptpickle.PickleErrorasperr:
print('Picklingerror:'+str(perr))
查看结果:
RESTART:C:/Users/ThinkPad/AppData/Local/Programs/Python/Python36-32/chapter4-134-pickle.py >>>importnester >>>nester.print_lol(new_man) Isthistherightroomforanargument? Noyouhaven't! When? Noyoudidn't! Youdidn't! Youdidnot! Ah!(takingouthiswalletandpaying)Justthefiveminutes. Youmostcertainlydidnot! Ohnoyoudidn't! Ohnoyoudidn't! Ohlook,thisisn'tanargument! Noitisn't! It'sjustcontradiction! ItIS! Youjustcontradictedme! YouDID! Youdidjustthen! (exasperated)Oh,thisisfutile!! Yesitis! >>>importos >>>os.getcwd() 'C:\\Users\\ThinkPad\\AppData\\Local\\Programs\\Python\\Python36-32' >>>
若是想保存new_man.txt到磁盘文件,可以加:
withopen('new_man.txt','w')asnew_man_file:
nester.print_lol(new_man,fn=new_man_file)
以上这篇使用pickle存储数据dump和load实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。