#!/usr/bin/python
# Filename: pickling.pyimport cPickle as p#import pickle as pshoplistfile = 'shoplist.data'# the name of the file where we will store the objectshoplist = ['apple', 'mango', 'carrot']# Write to the filef = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a filef.close()del shoplist # remove the shoplist
# Read back from the storagef = file(shoplistfile)
storedlist = p.load(f)print storedlist
首先,请注意我们使用了import..as语法。这是一种便利方法,以便于我们可以使用更短的模块名称。在这个例子中,它还让我们能够通过简单地改变一行就切换到另一个模块(cPickle或者pickle)!在程序的其余部分的时候,我们简单地把这个模块称为p。
为了在文件里储存一个对象,首先以写模式打开一个file对象,然后调用储存器模块的dump函数,把对象储存到打开的文件中。这个过程称为 储存 。
接下来,我们使用pickle模块的load函数的返回来取回对象。这个过程称为 取储存 。