Get yourself into a Python cPickle
Published: 15 Aug 2002 11:44 BST
Now I've looked in my kitchen and realised I also have pickles. I can add them to my list and reserialise it, and cPickle will remember what's contained there without duplicating the information:
inFridge.append("pickles")
print inFridge
The output of my print command now displays:
['ketchup', 'mustard', 'relish', 'pickles']
That looks right, so I have my script repickle the inFridge list and add it to the file:
FILE = open("fridge.txt", 'w')
cPickle.dump(inFridge, FILE)
FILE.close()
To get my information out of the file and back into a useable list, I simply open the file for reading and use the cPickle.load command to unpickle it. For the purposes of demonstration, I've used a new variable, inFridgeFile, to store the results:
FILE = open("fridge.txt", 'r')
inFridgeFile = cPickle.load(FILE)
FILE.close()
print inFridgeFile
The output of the print command displays:
['ketchup', 'mustard', 'relish', 'pickles']
When I repickled my list, cPickle recognised my original contents and didn't duplicate them. The inFridgeFile variable contains my information restored to its original list format.
To put a lid on it
You have various options for serialising your data in Python, including pickle and cPickle. My cPickle example showed that this implementation is truly handy, especially since these commands will preserve your original object and allow modifications to be made even after it has been processed. This functionality will keep you from being stuck in a pickle next time you're saving or transmitting objects.
Have your say instantly in the Tech Update forum.
Find out what's where in the new Tech Update with our Guided Tour.
Let the editors know what you think in the Mailroom.









