HomeComputer SciencePracticalClass 12Binary File Update

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 Update

AIM

To write a Python program to update specific records in a binary file.

ALGORITHM

  1. Start
  2. Import pickle module
  3. Read all records from the binary file into a list
  4. Search for the record to be updated
  5. Modify the required fields of the record
  6. Write the updated list back to the file
  7. Display confirmation message
  8. Stop

PROGRAM

import pickle

def update_record():
    try:
        # Read all records
        records = []
        with open('student.dat', 'rb') as file:
            try:
                while True:
                    record = pickle.load(file)
                    records.append(record)
            except EOFError:
                pass
        
        if not records:
            print("No records found!")
            return
        
        # Search for record to update
        roll_to_update = int(input("Enter roll number to update: "))
        found = False
        
        for i, record in enumerate(records):
            if record['roll'] == roll_to_update:
                print(f"Current record:")
                print(f"Name: {record['name']}")
                print(f"Roll: {record['roll']}")
                print(f"Marks: {record['marks']}")
                
                # Update fields
                new_name = input("Enter new name (or press Enter to keep current): ")
                new_marks = input("Enter new marks (or press Enter to keep current): ")
                
                if new_name:
                    records[i]['name'] = new_name
                if new_marks:
                    records[i]['marks'] = int(new_marks)
                
                found = True
                break
        
        if not found:
            print("Record not found!")
            return
        
        # Write updated records back to file
        with open('student.dat', 'wb') as file:
            for record in records:
                pickle.dump(record, file)
        
        print("Record updated successfully!")
        
    except FileNotFoundError:
        print("File not found!")
    except Exception as e:
        print(f"Error: {e}")

def display_records():
    try:
        with open('student.dat', 'rb') as file:
            print("All Records:")
            print("=" * 30)
            try:
                while True:
                    record = pickle.load(file)
                    print(f"Name: {record['name']}")
                    print(f"Roll: {record['roll']}")
                    print(f"Marks: {record['marks']}")
                    print("-" * 20)
            except EOFError:
                pass
    except FileNotFoundError:
        print("File not found!")

# Main program
if __name__ == "__main__":
    choice = input("1. Update record\n2. Display records\nEnter choice: ")
    if choice == '1':
        update_record()
    elif choice == '2':
        display_records()
    else:
        print("Invalid choice!")

OUTPUT

1. Update record

2. Display records

Enter choice: 1

Enter roll number to update: 101

Current record:

Name: John Doe

Roll: 101

Marks: 85

Enter new name (or press Enter to keep current): John Smith

Enter new marks (or press Enter to keep current): 90

Record updated successfully!

CONCLUSION

Thus, the program to update records in a binary file was successfully executed and verified.

VIVA QUESTIONS

  1. Why do we need to read all records before updating?

    Binary files don't support in-place updates easily. We read all records, modify in memory, then write back.

  2. What are the file modes 'rb' and 'wb'?

    'rb' opens file for reading in binary mode, 'wb' opens file for writing in binary mode.