1、pickle套件
(1)、將記憶體中的物件轉換為文字流:
import pickle # define class class Bird(object): have_feather = True way_of_reproduction = 'egg' summer = Bird() # construct an object picklestring = pickle.dumps(summer) # serialize object
使用pickle.dumps()方法可以將物件summer轉換成了字串 picklestring(也就是文字流)。隨後我們可以用普通文字的儲存方法來將該字串儲存在檔案(文字檔案的輸入輸出)。
當然,我們也可以使用pickle.dump()的方法,將上面兩部合二為一:
import pickle # define class class Bird(object): have_feather = True way_of_reproduction = 'egg' summer = Bird() # construct an object fn = 'a.pkl' with open(fn, 'w') as f: # open file with write-mode picklestring = pickle.dump(summer, f) # serialize and save object
對象summer存放在文件a.pkl
(2)、重建對象
首先,我們要從文本中讀出文本,儲存到字串(文本檔的輸入輸出)。然後使用pickle.loads(str)的方法,將字串轉換成為物件。要記得,此時我們的程式中必須已經有了該物件的類別定義。
import pickle # define the class before unpickle class Bird(object): have_feather = True way_of_reproduction = 'egg' fn = 'a.pkl' with open(fn, 'r') as f: summer = pickle.load(f) # read file and build object
import cPickle as pickle
就不需要再做任何改動了。