1

I have created(still working on it) a simple phonebook CLI application using linked list in python.In main method I have created an object called phone and added some names and numbers.I need to save this object as .ser file and it should be able to open that again and make changes to that. I did that in java using Serialization(including file streams). But it is difficult to find a way in python to do that.Could someone give me a code to serialize that object and deserialize also?

My phonebook CLI application code is below,

class Node:
    def __init__(self,name,number):
        self.name = name
        self.number = number
        self.next = None
class List:
    def __init__(self):
        self.head = None
    def InsertNumber(self,name,number):
        if self.head == None:
            self.head = Node(name,number)
        else:
            newNode = Node(name,number)
            temp = self.head
            temp2 = self.head
            if(newNode.name<self.head.name):
                newNode.next = self.head
                self.head = newNode
            else:
                while(temp is not None and newNode.name >= temp.name):
                    temp2 = temp
                    temp = temp.next
                temp2.next = newNode
                newNode.next = temp
    def Display(self):
        temp = self.head
        while(temp is not None):
            print("{0:<15}{1:<15}".format(temp.name,temp.number),end='\n')
            temp = temp.next
def Main():
    phone = List()
    phone.InsertNumber("Jeewantha","234242")
    phone.InsertNumber("Ahiru","r34535")
    phone.InsertNumber("Akila","52324")
    phone.InsertNumber("Zahira","24242")
    phone.InsertNumber("Amasha","234242")
    phone.Display()

if __name__ == "__main__":
    Main()
Jeewantha Lahiru
  • 324
  • 2
  • 4
  • 15

1 Answers1

2

You can use pickle built in module that implements binary protocols for serializing and de-serializing a Python object structure.

To serialize the phone object,

import pickle

with open("phone.pickle", "wb") as f:
    pickle.dump(phone, f)

To deserialize the serialized object use,

with open("phone.pickle", "rb") as f:
    phone = pickle.load(f)
    phone.Display()
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53