Tuesday, September 10, 2024
HomeDefinitionsPickle and cPickle in Python

Pickle and cPickle in Python

Serializing and De-serializing a Python object structure can be done with pickle . Pickle module serialize the object before writing it to specific file. converting the python objects such as list, dict etc into stream of characters is called as pickling. Information contained by thus converted character stream can be used to reconstruct those object in another python script.

Before getting started, do consider the fact that pickle module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.

Lets get started with pickling up python list.

First of all you need to import pickle module as

import pickle

Now, import the pickled object and assign it to a variable

a = ['test value','test value 2','test value 3']
a
['test value','test value 2','test value 3']

file_Name = "testfile"
# open the file for writing
fileObject = open(file_Name,'wb') 

# this writes the object a to the
# file named 'testfile'
pickle.dump(a,fileObject)   

# here we close the fileObject
fileObject.close()
# we open the file for reading
fileObject = open(file_Name,'r')  
# load the object from the file into var b
b = pickle.load(fileObject)  
b
['test value','test value 2','test value 3']
a==b
True


There is also a predecessor to python named cpickle and according to official documentation it is 1000 times faster because of use of C-language.

For more on documentation of Pickle and CPickle click here

Thanks.

datasagarhttp://www.DataSagar.com
The author of this blog post is a technology fellow, an IT entrepreneur, and Educator in Kathmandu Nepal. With his keen interest in Data Science and Business Intelligence, he writes on random topics occasionally in the DataSagar blog.
RELATED ARTICLES
- Advertisment -

Most Popular