#!/usr/bin/python
# Filename: pickling.py
import cPickle 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 = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
(源文件:code/pickling.py)
輸出
$ python pickling.py
['apple', 'mango', 'carrot']
它如何工作
首先,請注意我們使用了 import..as 語法。這是一種便利方法,以便于我們可以使用更短的模塊名稱。在這個例子中,它還讓我們能夠通過簡單地改變一行就切換到另一個模塊(cPickle 或者 pickle)!在程序的其余部分的時候,我們簡單地把這個模塊稱為 p。
為了在文件里儲存一個對象,首先以寫模式打開一個 file 對象,然后調(diào)用儲存器模塊的 dump 函數(shù),把對象儲存到打開的文件中。這個過程稱為 儲存 。
接下來,我們使用 pickle 模塊的 load 函數(shù)的返回來取回對象。這個過程稱為 取儲存 。