2009年8月8日 星期六

cPickle - 儲存python物件至檔案 / 從檔案中讀取python物件

cPickle可以在檔案中保存python物件,讀取時不用再另外寫parser重組資訊。
import cPickle

def ObjectSaveToFile(filePath, obj):
    """\
ObjectSaveToFile(filePath, obj)
    Save a python object into file.

    Parameters:
        filePath     ( type = string)
        obj          ( type = any python object like dict )"""
    fileGen = open(filePath, 'w')
    cPickle.dump(obj, fileGen, True)
    fileGen.close()

def ObjectLoadFromFile(filePath):
    """\
ObjectSaveToFile(filePath, obj)
    Load a python object from file.
    Parameters:
        filePath     ( type = string)
    Returns:
        obj          ( type = any python object like list, dict )"""
    fileRead = open(filePath, 'r')
    obj = cPickle.load(fileRead)
    fileRead.close()
    return obj


ObjectSaveToFile函數設計成在檔案中保存單一物件。雖然cPickle支援儲存多個物件至檔案中,但讀取時也得照順序讀。這會造成程式維護的相容性問題:當改變讀取或存入物件順序後,舊的檔案便無法再讀取,或是得特別保留讀取舊檔案格式的程式碼。

因此我會以字典(dict)物件將多個物件包成單一物件,以key來讀取各別物件。objDict.get(key, defaultObj)可用來保持與舊檔案格式的相容,當沒有找到某個key時,將對應物件設定成預設值。

沒有留言: