Skip to main content

GRADE XII - Binary File Manipulation (Dictionary)

 

Binary File Manipulation (Dictionary)

import pickle

from os import remove, rename

 

def Create():

    with open("emp.dat", "wb") as File:

        while True:

            Eno = int(input("Eno: "))

            Name = input("Name: ")

            Sal = float(input("Salary: "))

            Dept = input("Department: ")

            Emp = {"Eno": Eno, "Name": Name, "Sal": Sal, "Dept": Dept}

            pickle.dump(Emp, File)

            Ans = input("More (Y/N)? ")

            if Ans in 'nN':

                break

 

def Disp():

    try:

        with open("emp.dat", "rb") as File:

            while True:

                Emp = pickle.load(File)

                print(Emp)

    except EOFError:

        pass

    except FileNotFoundError:

        print("File not found.")

    except Exception as e:

        print("An error occurred:", e)

 

 

def searcheno():

    Seno = int(input("Enter Employee no to search - "))

    found = False

    try:

        with open("emp.dat", "rb") as File:

            while True:

                Emp = pickle.load(File)

                if Emp["Eno"] == Seno:

                    print("Record Found:", Emp)

                    found = True

                    break

    except EOFError:

        if not found:

            print("No such Record Found")

    except FileNotFoundError:

        print("File not found.")


def searchenm():

    Senm = input("Enter Employee name to search - ")

    found = "n"

    try:

        with open("emp.dat", "rb") as File:

            while True:

                Emp = pickle.load(File)

                if Emp["Name"] == Senm:

                    print(Emp)

                    found = "y"

    except EOFError:

        pass

   

    if found == "n":

        print("No such Record Found")

 

import pickle

 

def CountDept():

    ctr = 0

    Sdept = input("Enter Department - ")

    try:

        with open("emp.dat", "rb") as File:

            while True:

                Emp = pickle.load(File)

                if Emp["Dept"] == Sdept:

                    print(Emp)

                    ctr += 1

    except EOFError:

        pass

 

    print("No. of Employees in", Sdept, "-", ctr)

 

def Countsal():

    ctr = 0

    try:

        with open("emp.dat", "rb") as File:

            while True:

                Emp = pickle.load(File)

                if Emp["Sal"] > 6000:

                    # print(Emp)  # Uncomment if you want to display each employee

                    ctr += 1

    except EOFError:

        pass

    print("No. of employees with Salary > 6000 -", ctr)

 

def highestsal():

    try:

        with open("emp.dat", "rb") as file:

            # Read the first record to initialize highest salary

            Emprec = pickle.load(file)

            hsal = Emprec["Sal"]

 

            # Read remaining records

            while True:

                Emprec = pickle.load(file)

                if Emprec["Sal"] > hsal:

                    hsal = Emprec["Sal"]

    except EOFError:

        print("Highest Salary -", hsal)

    except FileNotFoundError:

        print("File not found.")

    except Exception as e:

        print("Error:", e)

 

def EditOnEmpno():

    file = open("emp.dat", "rb")

    tempfile = open("temp.dat", "wb")

    found = "n"

    Seno = int(input("Enter Employee no to Edit - "))

     try:

        while True:

            Emp = pickle.load(file)

            if Emp["Eno"] == Seno:

                eno = Emp["Eno"]

                Name = input("Edited Name: ")

                Sal = float(input("Edited Salary: "))

                Dept = input("Edited Department: ")

                Empnew = {"Eno": eno, "Name": Name, "Sal": Sal, "Dept": Dept}

                found = "y"

                pickle.dump(Empnew, tempfile)

            else:

                pickle.dump(Emp, tempfile)

    except EOFError:

        file.close()

        tempfile.close()

 

    if found == "n":

        print("No such record")

        remove("temp.dat")

    else:

        remove("emp.dat")

        rename("temp.dat", "emp.dat")

        print("Record updated successfully.")

 

def Editname():

    file = open("emp.dat", "rb")

    tempfile = open("temp.dat", "wb")

    found = "n"

    nm = input("Enter Employee name to Edit - ")

    try:

        while True:

            Emp = pickle.load(file)

            if Emp["Name"] == nm:

                eno = Emp["Eno"]

                Name = input("Edited Name: ")

                Sal = float(input("Edited Salary: "))

                Dept = input("Edited Department: ")

                Empnew = {"Eno": eno, "Name": Name, "Sal": Sal, "Dept": Dept}

                found = "y"

                pickle.dump(Empnew, tempfile)

            else:

                pickle.dump(Emp, tempfile)

    except EOFError:

        file.close()

        tempfile.close()

 

    if found == "n":

        print("No such record")

        remove("temp.dat")

    else:

        remove("emp.dat")

        rename("temp.dat", "emp.dat")

        print("Record updated successfully.")

 

def EditOnrecno():

    file = open("emp.dat", "rb")

    tempfile = open("temp.dat", "wb")

    found = "n"

    n = int(input("Enter record no to Edit - "))  # record number starts from 1

    rec = 1  # record counter

   

    try:

        while True:

            Emp = pickle.load(file)

            if rec == n:

                eno = Emp["Eno"]

                Name = input("Edited Name: ")

                Sal = float(input("Edited Salary: "))

                Dept = Emp["Dept"] 

                Empnew = {"Eno": eno, "Name": Name, "Sal": Sal, "Dept": Dept}

                found = "y"

                pickle.dump(Empnew, tempfile)

            else:

                pickle.dump(Emp, tempfile)

            rec += 1

    except EOFError:

        file.close()

        tempfile.close()

 

    if found == "n":

        print("No such record")

        remove("temp.dat")

    else:

        remove("emp.dat")

        rename("temp.dat", "emp.dat")

        print("Record updated successfully.")

 

def EditOndept():

    file = open("emp.dat", "rb")

    tempfile = open("temp.dat", "wb")

    found = "n"

   

    Sdept = input("Enter record no to Edit - ") 

    rec = 1 

 

    try:

        while True:

            Emp = pickle.load(file)

            if Emp["Dept"] == Sdept:

                eno = Emp["Eno"]

                Name = input(" Edited Name :")

                Sal = float(input(" Edited Salary:"))

                Dept = input("Edited Department :")

                Empnew = {"Eno": eno, "Name": Name, "Sal": Sal, "Dept": Dept}

                found = "y"

                pickle.dump(Empnew, tempfile)

            else:

                pickle.dump(Emp, tempfile)

            rec += 1 

    except EOFError:

        file.close()

        tempfile.close()

 

    if found == "n":

        print("No such record")

        remove('temp.dat')

    else:

        remove('emp.dat')

        rename('temp.dat', 'emp.dat')

        print("Record updated successfully.")

while True:

    CH = input(

        "1. Create\n"

        "2. Display\n"

        "3. Search by Emp No\n"

        "4. Search by Emp Name\n"

        "5. Count Records of a Given Department\n"

        "6. Modify by Emp No\n"

        "7. Display Highest Salary\n"

        "8. Quit\n"

        "Enter your choice (1-8): "

    )

 

    if CH == '1':

        Create()

    elif CH == '2':

        Disp()

    elif CH == '3':

        searcheno()

    elif CH == '4':

        searchenm()

    elif CH == '5':

        CountDept()

    elif CH == '6':

        EditOnEmpno()

    elif CH == '7':

        highestsal()

    elif CH == '8':

        break

    else:

        print("Invalid choice. Please enter a number between 1 and 8.")


CBSE QUESTION WITH SOL:
QUE: Mr. Srikanth, an IT developer of a company, needs to maintain records of employees in a binary file EMP.DAT. Each record is stored in the following format:

[E_ID, E_Name, Designation, Salary]
Example: [101, "Ravi", "PGT", 98000], [102, "Roja", "TGT", 89000], …

Write Python functions to perform the following operations:

(i) Add_emp()
To input details of employees and store the records in the binary file EMP.DAT using the pickle module.

(ii) Update_sal()
To increase the salary of all employees having designation "PGT" by 10% and update the changes in the file.
(Use a temporary file along with remove() and rename() functions.)



SOL:
import pickle
from os import remove, rename

# Function to add employee records
def Add_emp():
    f = open("EMP.DAT", "wb")
    n = int(input("Enter number of employees: "))
    
    for i in range(n):
        E_ID = int(input("Enter Employee ID: "))
        E_Name = input("Enter Name: ")
        Desig = input("Enter Designation: ")
        Salary = float(input("Enter Salary: "))
        
        rec = [E_ID, E_Name, Desig, Salary]
        pickle.dump(rec, f)
    
    f.close()
    print("Records added successfully.")


# Function to update salary of PGT employees
def Update_sal():
    f = open("EMP.DAT", "rb")
    temp = open("TEMP.DAT", "wb")
    
    try:
        while True:
            rec = pickle.load(f)
            
            if rec[2] == "PGT":
                rec[3] = rec[3] * 1.10   # 10% increment
            
            pickle.dump(rec, temp)
    
    except EOFError:
        pass
    
    f.close()
    temp.close()
    
    # Delete original file and rename temp file
    remove("EMP.DAT")
    rename("TEMP.DAT", "EMP.DAT")
    
    print("Salary updated successfully.")

WITH DICTIONARY

import pickle
from os import remove, rename

# Function to add employee records using dictionary
def Add_emp():
    f = open("EMP.DAT", "wb")
    n = int(input("Enter number of employees: "))
    
    for i in range(n):
        emp = {}
        emp["E_ID"] = int(input("Enter Employee ID: "))
        emp["E_Name"] = input("Enter Name: ")
        emp["Desig"] = input("Enter Designation: ")
        emp["Salary"] = float(input("Enter Salary: "))
        
        pickle.dump(emp, f)
    
    f.close()
    print("Records added successfully.")


# Function to update salary of PGT employees
def Update_sal():
    f = open("EMP.DAT", "rb")
    temp = open("TEMP.DAT", "wb")
    
    try:
        while True:
            emp = pickle.load(f)
            
            if emp["Desig"] == "PGT":
                emp["Salary"] = emp["Salary"] * 1.10   # 10% increase
            
            pickle.dump(emp, temp)
    
    except EOFError:
        pass
    
    f.close()
    temp.close()
    
    remove("EMP.DAT")
    rename("TEMP.DAT", "EMP.DAT")
    
    print("Salary updated successfully.")

Comments