Class XII: Python Data File Handling 20

Delete a record from binary file using Bank Account no

 

import pickle
import os

#function definition
def delete_accno():
     try:
          z=0
          tr=int(input("Enter accno to delete "))
          f=open("bank","rb")
          tf=open("temp","wb")
          print("Accno","Name","Balance")
          while True:
               rec=pickle.load(f)
               if rec[0]==tr:
                    z=1
                    print(rec[0],rec[1],rec[2])
               else:
                    pickle.dump(rec,tf)

     
     except EOFError:
          f.close()
          tf.close()
          if z==0:
               print("Record not found")
          else:
               os.remove("bank")
               os.rename("temp","bank")

     except IOError:
          print("Unable to open the file")

#function calling
delete_accno()

Update a record from binary file using Bank Account no

 

import pickle
import os

#function definition
def update_accno():
     try:
          z=0
          tr=int(input("Enter Accno to update "))
          f=open("bank","rb")
          tf=open("temp","wb")
          print("Accno","Name","Balance")
          while True:
               rec=pickle.load(f)
               if rec[0]==tr:
                    z=1
                    print("Old Record")
                    print(rec[0],rec[1],rec[2])
                    print("Enter new data ")
                    accno=int(input("Enter Accno "))
                    name=input("Enter name ")
                    name=name.upper()
                    bal=float(input("Enter Balance "))
                    rec=[accno,name,bal]
               pickle.dump(rec,tf)

     
     except EOFError:
          f.close()
          tf.close()
          if z==0:
               print("Record not found")
          else:
               os.remove("bank")
               os.rename("temp","bank")

     except IOError:
          print("Unable to open the file")

#function calling
update_accno()