vishavjeet

singh.vishavjeet11@gmail.com

What is Pickling in Python?

Posted on June 30, 2021



Python pickle module is used for serializing and de-serializing a Python object structure.

Pickling” is the process whereby a Python object is converted into a byte stream,

and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object

Example: 

import pickle

def storeData():

  db = {}
  db['vishavjeet'] = {'key': 'Vishavjeet', 'name': 'Vishavjeet Singh', 'age': 28, 'pay': 40000}
  db['Scarpion'] = {'key': 'Scarpion', 'name': 'Scarpion', 'age': 28, 'pay': 50000}
  # Its important to use binary mode
  with open('my_pickle_file', 'ab') as f:
    pickle.dump(db, f) # source, destination

def loadData():
  # for reading also binary mode is important
  with open('my_pickle_file', 'rb') as f:
    db = pickle.load(f)

  for keys in db:
    print(keys, '=>', db[keys])

storeData() # pickling
loadData() # unpickling


Sign In for comment and like the post.