Class XII: Python Data File Handling 18

Binary File to maintain Bank records

 

Add record in a Binary File

 

import pickle
import os

#function definition
def add_record():
     try:
          if os.path.isfile("bank"):
               f=open("bank","ab")
          else:
               f=open("bank","wb")
          accno=int(input("Enter Accno "))
          name=input("Enter name ")
          name=name.upper()
          bal=float(input("Enter Balance "))
          rec=[accno,name,bal]
          pickle.dump(rec,f)
          print("Bank Customer Record added in file")
     except EOFError:
          f.close()

#function calling
add_record()

Display all the records from binary file

 

import pickle

#function definition
def bank_dispall():
     try:
          f=open("bank","rb")
          print("Accno","Name","Balance")
          while True:
               rec=pickle.load(f)
               print(rec[0],rec[1],rec[2])

     
     except EOFError:
          f.close()
     except IOError:
          print("Unable to open the file")

#function calling
bank_dispall()