HomeComputer SciencePracticalClass 12Binary File Search Display Records

Class 12 Programs

Quick Tips

  • • Import random module for number generation
  • • Use randint(1, 6) for dice simulation
  • • Handle user input validation properly

Binary File Search & Display Records

AIM

To write a Python program to search and display all records from a binary file that match specific criteria.

ALGORITHM

  1. Start
  2. Import pickle module
  3. Define search criteria
  4. Open binary file in read mode
  5. Read all records using pickle.load()
  6. Filter records based on search criteria
  7. Display matching records in formatted manner
  8. Close the file
  9. Stop

PROGRAM

import pickle

def display_all_records():
    try:
        with open('employee.dat', 'rb') as file:
            print("All Employee Records:")
            print("=" * 50)
            record_count = 0
            
            try:
                while True:
                    record = pickle.load(file)
                    record_count += 1
                    print(f"Record {record_count}:")
                    print(f"ID: {record['id']}")
                    print(f"Name: {record['name']}")
                    print(f"Department: {record['dept']}")
                    print(f"Salary: {record['salary']}")
                    print("-" * 30)
            except EOFError:
                print(f"Total records displayed: {record_count}")
                
    except FileNotFoundError:
        print("File not found!")
    except Exception as e:
        print(f"Error: {e}")

def search_by_department():
    try:
        with open('employee.dat', 'rb') as file:
            dept_name = input("Enter department to search: ")
            print(f"Employees in {dept_name} department:")
            print("=" * 40)
            found = False
            
            try:
                while True:
                    record = pickle.load(file)
                    if record['dept'].lower() == dept_name.lower():
                        print(f"Name: {record['name']}")
                        print(f"ID: {record['id']}")
                        print(f"Salary: {record['salary']}")
                        print("-" * 25)
                        found = True
            except EOFError:
                if not found:
                    print("No records found for this department!")
                    
    except FileNotFoundError:
        print("File not found!")
    except Exception as e:
        print(f"Error: {e}")

# Main program
if __name__ == "__main__":
    choice = input("1. Display all records\n2. Search by department\nEnter choice: ")
    if choice == '1':
        display_all_records()
    elif choice == '2':
        search_by_department()
    else:
        print("Invalid choice!")

OUTPUT

1. Display all records

2. Search by department

Enter choice: 2

Enter department to search: IT

Employees in IT department:

========================================

Name: Alice Johnson

ID: 101

Salary: 75000

-------------------------

CONCLUSION

Thus, the program to search and display records from a binary file was successfully executed and verified.

VIVA QUESTIONS

  1. What is EOFError in Python?

    EOFError is raised when the input() function hits an end-of-file condition or when pickle.load() reaches the end of file.

  2. How do you handle file exceptions in Python?

    Use try-except blocks to catch FileNotFoundError, IOError, and other file-related exceptions.