Latest News

Monday, May 27, 2019

What is Python Pickling ?

Python pickle module is used for serializing and de-serializing a Python object structure.Any object in Python can be pickled so that it can be saved on disk. 


  • It  serializes the object first before writing it to file. 
  • It is a way to convert a python object (list, dict, etc.) into a character stream. 
  • It helps to reconstruct the object in another python script.

import pickle
  
def storeData():
    # initializing data to be stored in db
    Omkar = {'key' : 'Omega', 'name' : 'Hello Omega',
    'age' : 99, 'pay' : 40000}
    Jagdish = {'key' : 'Alfa', 'name' : 'Hello Alfa',
    'age' : 55, 'pay' : 50000}
  
    # database
    db = {}
    db['Omega'] = Omega
    db['Alfa'] = Alfa
      
    # Its important to use binary mode
    dbfile = open('examplePickle', 'ab')
      
    # source, destination
    pickle.dump(db, dbfile)                     
    dbfile.close()
  
def loadData():
    # for reading also binary mode is important
    dbfile = open('examplePickle', 'rb')     
    db = pickle.load(dbfile)
    for keys in db:
        print(keys, '=>', db[keys])
    dbfile.close()
  
if __name__ == '__main__':
    storeData()
    loadData()
  • Google+
  • Pinterest
NEXT »

No comments

Post a Comment