直接上代码吧
#-*-coding:utf-8 import os if os.path.exists(‘d:\\cpickle.data‘): os.remove(‘d:\\cpickle.data‘) import cPickle as P shoplist=[‘apple‘,‘banana‘,‘pear‘] P.dump(shoplist,file(‘d:\\cpickle.data‘,‘w‘)) f=file(‘d:\\cpickle.data‘) while True: content=f.readline() if len(content)==0: break; print(content) f.seek(0) #重新定位到文件头,否则报错 shoplist2=P.load(f) print(shoplist2)
输出:
(lp1
S‘apple‘
p2
aS‘banana‘
p3
aS‘pear‘
p4
a.
[‘apple‘, ‘banana‘, ‘pear‘]
这个华丽丽的功能名字叫做:pickle ,建议用cPickle,速度是pickle的100倍。可以保存任意Python对象。
Python Special Syntax 8: 序列化与反序列化-->华丽丽的叫 pickle(泡菜?!),布布扣,bubuko.com