pickle使用

# filename:picklng.py
import pickle as p
#import pickle as p
shoplistfile = 'shoplist.data'
#the name of the file where we will store the object

shoplist = ['apple','mango','carrot']

#write to the file
f=open(shoplistfile,'wb') #wb, 开启二进制,否则会报错TypeError: must be str, not bytes
p.dump(shoplist,f) #dump the object to a file
f.close()

del shoplist # remove the shoplist

#read from the storage
f=open(shoplistfile,"rb") #如果缺少rb,则会报错:TypeError: 'str' does not support the buffer interface
storedlist=p.load(f)
print(storedlist)

原文地址:https://www.cnblogs.com/amy2012/p/3719027.html