Monday, July 20, 2009

Pickle Tutorial

What pickle does is take a python variable and serialize it (copy the binary from memory to the hard drive) this is the easiest method for backing up data for program use.

First step is to create a class to use the data. Even though Pickle can store all kinds of python basic variables, encapsulating backed up data within a class helps code readability.

class MrPickle():

Then you want to add a variable to it

class MrPickle():
data = []


Then you want to allow it to save itself to disk.

import Pickle

class MrPickle():
data = []

def save():
pickle.dump(self.data,open('mofo.dip','w'))

braking it down:
import Pickle = import the pickle library
pickle.dump() = save function
mrP.data = does not save full instance just basic variables
open() = opens a file for reading or writing. cannot append part files.
'mofo.dip' = file name
'w' = w for write r for read

Loading is more complex. Keep in mind if the file does not exist, open() when used in read mode will throw an exception.

import Pickle

class MrPickle():
data = []

def save():
pickle.dump(self.data,open('mofo.dip','w'))

def load():
try:
pData = pickle.load(open('mofo.dip','r'))
except:
self.save()

Explanation: first it tries to read the file and load it into self.data variable. If file does not exist it throws an exception and calls the class save function. Which then creates a file containing a blank array variable. Im asuming the file is saved to a source file named MaPickle.py

Now to use this class template:

pMan = MaPickle.MrPickle()
pMan.load()

First run creates a blank mofo.dip file. By manipulating the variable pMan.data then runing pMan.save(), any data in the variable will be re-loaded next time the program is run.

No comments:

Post a Comment