Class XII: Python Data File Handling | Binary Files

Binary File to maintain Employee records

Employee Data maintained :
employee code
employee name
employee salary

Add record in a Binary File

 

import pickle
import os

#function definition
def add_record():
     try:
          if os.path.isfile("emp"):
               f=open("emp","ab")
          else:
               f=open("emp","wb")
          empno=int(input("Enter Emp no "))
          name=input("Enter name ")
          name=name.upper()
          sal=float(input("Enter Salary "))
          rec=[empno,name,sal]
          pickle.dump(rec,f)
          print("Employee Record added in file")
     except EOFError:
          f.close()

#function calling
add_record()

Display all the records from binary file

 

import pickle

#function definition
def emp_dispall():
     try:
          f=open("emp","rb")
          print("Empno","Name","Salary")
          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
emp_dispall()