Python Pickle Object Serialization Example

Pickle is a python module which implements the protocol for serializing and deserializing python object. It can converts python objects into binary format data and then save the object in hard disk. It can also load the already saved data from disk file and restore it back to original python object. This is useful for storing large amounts of information.

1. Pickle Usage.

1.1 Import Module.

import pickle
import numpy as np

1.2 Serialize And Deserialize.

  1. serialize ´╝Üpickle.dump(a, open(“test_file.pkl”, “wb”))
  2. deserialize : pickle.load(open(“test_file.pkl”, “rb”))

2. Example.

import pickle
# numpy is a python numeric module 
import numpy as np

# Create a two dimension array.
array_original = np.array([[1, 2, 3], [4, 5, 6]])

# Serialize the array object to a file array.pkl
pickle.dump(array_original, open("array.pkl", "wb"))

# Deserialize the array data from file.
array_deserialize = pickle.load(open("array.pkl", "rb"))

# Check if the two array content is same or not.
print(array_original == array_deserialize)

# Use pickle to save a dictionary object to disk. 
pickle.dump({"name": "kevin"}, open("dict_example.pkl", "wb"))

# Serialize and deserialize complex object.
# Create two array.
array_one = np.ones(2, 3) 
array_two = np.ones(2)
# Create a dict object.
data = { "array_one": array_one, "array_two": array_two }
# Serialize d to file.
pickle.dump(d, open("dict_example.pkl", "wb"))
# Load the data back. 
load_back_data = pickle.load(open("dict_example.pkl", "rb"))
# Print the data.

1 Comment

Comments are closed.