Home › Forums › Python Programming › Pickling and unpickling in python
- This topic has 0 replies, 1 voice, and was last updated 12 years, 1 month ago by
Humble.
Viewing 1 post (of 1 total)
-
AuthorPosts
-
Humble
Keymasterpickling and unpickling is a very useful feature in python which is used for serialization and de-serialization. Sometime its necessary to convert an object strucutre to a byte stream and get it back to the original state once its done . This is achieved with the help of pickling and unpickling .
Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy.
For ex:
>>>> import pickle >>> pickle.__doc__ 'Create portable serialized representations of Python objects.\n\nSee module cPickle for a (much) faster implementation.\nSee module copy_reg for a mechanism for registering custom picklers.\nSee module pickletools source for extensive comments.\n\nClasses:\n\n Pickler\n Unpickler\n\nFunctions:\n\n dump(object, file)\n dumps(object) -> string\n load(file) -> object\n loads(string) -> object\n\nMisc variables:\n\n __version__\n format_version\n compatible_formats\n\n'
>>> with open('/tmp/hum', 'w') as f: ... tran_dict = {1 : 'monday' , 2 : 'tuesday', 3:'wednesday'} ... pickle.dump(tran_dict, f) ... >>> Once its 'pickled' , if you cross-check the file you can see:>@humbles-lap ~]$ cat /tmp/hum (dp0 I1 S'monday' p1 sI2 S'tuesday' p2 sI3 S'wednesday' p3 s. [@humbles-lap ~]$ Now to unpickle or to get it back , you can try something like below::
>>>> fDes = open('/tmp/hum','r') >>> pickle.load(fDes) {1: 'monday', 2: 'tuesday', 3: 'wednesday'} One of the use case for using pickle is , if you want to transfer dictionary object over network ... There are other options to do that , for ex: json.. how-ever sometime this may be handy... -
AuthorPosts
Viewing 1 post (of 1 total)