python中提供一个pickle 标准类 来 存储/读取 任意的对象。
如下:

import pickle as p

class PickleTest:

    def __init__(self,o,filename):
        if not 0:
            self.obj=o
            self.filename=filename

    def dump(self):
        print 'save data ',self.obj,' >> ',self.filename
        f = file(filename,'w')
        p.dump(self.obj,f)

    def load(self):
        f = file(self.filename)
        s = p.load(f)
        print 'load data from ',self.filename,' >>',s
        return s
if __name__=='__main__':
    filename = 'test.data'
    obj = {'p1':[0,1,2,3],'p2':(1,2,3),'p3':{'1':1,'2':2},'p4':'str'}
    test = PickleTest(obj,filename)
    test.dump()
    test.load()

同时也提供另外一个类cPickle,是c写的,速度当然会快很多。
只需将如下

import pickle as p

换成

import cPickle as p

即可

<!----><!----><!---->
分享到:
评论