How to Pickle a Python? Huh?
Written by
on .What do pickles and pythons have in common? Well, I'll get to that in a second. First, let's talk about application data. A key part of every program design is "how and where do I store my data". I have considered many different options for the OpenShot Video Editor, including XML, Embedded MySQL, and SqlLite.
The problem with using any of these methods, is that I will be responsible for writing all the data access code. That would include iterating through my complex object model, trying to persist all the various variables, objects, collections, and lists when the user clicks "save". Then when the user returns and "opens" their project, I would have to reverse the process. This can be a very tedious and buggy process. There has to be an easier way, right?
Here is where the pickles come into this story. There is a "pickle" module (as well as a faster cPickle module) that comes built in to Python. It is responsible for serializing and deserializing any Python object, including complex custom objects.
Here are some examples of how the cPickle module works:
Saving a custom object to the file system:
import cPickle as pickle
myFile = file(file_path, "wb")
pickle.dump(your_custom_object, myFile, True)
Loading a custom object from the file system:
import cPickle as pickle
myFile = file(file_path, "rb")
your_custom_object = pickle.load(myFile)