Pacific-Design.com

    
Home Index

1. Python

2. Pickle Shelve

Python / Pickle Shelve /

#!/usr/bin/python

import time, pickle, shelve

class PickleShelve(object):
    def myPickle(self):

        print "--- Writing Data Structure into Pickle ---"    
        f = open("pickle.dat", "wb")
        dat1 = ["one1", "two1", "three1", "four1", "five1"]
        dat2 = ["one2", "two2", "three2", "four2", "five2"]
        pickle.dump(dat1, f)
        pickle.dump(dat2, f)
        f.close()
        time.sleep(1)
     
        print "--- Reading Data Structure from Pickle ---"
        f = open("pickle.dat", "rb")
        dat1 = pickle.load(f)
        dat2 = pickle.load(f)
        f.close()

    def myShelve(self):

        print "--- Writing Data Structure into Shelve ---"
        s = shelve.open("shelve.dat","w")
        s["row1"] = ["column11", "column12", "column13", "column14"]
        s["row2"] = ["column21", "column22", "column23", "column24"]
        s.sync()
        s.close()

        time.sleep(1)
        print "--- Reading Data Structure from Shelve ---"
        s = shelve.open("shelve.dat","r")
        print ("row1 =", s["row1"])
        print ("row2 =", s["row2"])
        s.close()

if __name__ == "__main__":
    print "Pickle / Shelve Demo Starting "
    ps = PickleShelve()
    ps.myPickle()
    ps.myShelve()