Saturday, January 21, 2012

Python Note 7 (the pickle module)

In python we can use serialization functionality using pickle module. it can save live instances of objects to files and retrieve object instances from pickled files.
Code:
import pickle

class Transaction : 
 def __init__(self,userName,trnsID,payment):
  self.userName=userName
  self.trnsID=trnsID
  self.payment=payment
 
 def __del__(self):
  print("Destructed!")
 
 def getPaymentValue(self):
  return self.payment
 
 def getUserName(self) :
  return self.userName
#end of the class

#persisting an object
hndl=open("transactionpickl.dat","wb") #'wb' means writing bytes
t1=Transaction("Kanishka",1232333,22480.75)
pickle.dump(t1,hndl)
print("Objet pickled successfully!")
hndl.close()

#retrieving an object
hndl=open("transactionpickl.dat","rb") ##'wb' means reading bytes
trObj=pickle.load(hndl)
print("__________________________")
print("Data from pickled object!")
print("User Name : {} ".format(trObj.userName))
print("Transaction ID : {} ".format(trObj.trnsID))
print("Payment Name : {} ".format(trObj.payment))
hndl.close()
Note : Remember that we have to use "wb" and "rb" as file modes of the file handler. because pickler use byte reading and byte writing operations to "pickle" and given object to the file system. so we can't use default "String" read and write modes.
Output:
C:\Users\Kanishka\Desktop>python pickletest.py
Objet pickled successfully!
__________________________
Data from pickled object!
User Name : Kanishka
Transaction ID : 1232333
Payment Name : 22480.75
Destructed!
Destructed!

C:\Users\Kanishka\Desktop>

0 comments:

Post a Comment

© kani.stack.notez 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis