How To Write an Object To a File in Python.

Share:



To write an object into a file/module you must have to create a Class.

class Employee:

Then define an instance method.

def assing(self,idno,name,salary):
        self.idno=idno
        self.name=name
        self.salary=salary

Then define a display method.

def display (self):
        print("Idno :",self.idno)
        print("Name :", self.name)
        print("Salary :",self.salary)

Then create an object and assing to a variable.

emp=Employee()
emp.assing(101,"Arbaaz Bangash",600000.00)

Now write an OBJECT to a FILE.

import pickle as pi
file=open("Employee.txt","wb")
pi.dump(emp,file)
file.close()
print("Operation complete")

Done!

No comments