Thursday, September 28, 2023
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']
['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'

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

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


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.
- Advertisment -

Most Popular