The following Python program is designed to update the phone number of a…

2026

The following Python program is designed to update the phone number of a specific person in a binary file named directory.dat. The file stores records as lists in the format [Name, Phone]. The function searches for a record matching Name. If found, it updates the phone number and saves the changes back to the file.

import pickle

def Update(Name, New_Phone):
    Found = False
    Records = []
    try:
        ______ (A) ______ as File:
            while True:
                try:
                    Rec = ______ (B) ______
                    if Rec[0] == Name:
                        Rec[1] = New_Phone
                        Found = True
                    Records.append(Rec)
                except EOFError:
                    break

        if Found:
            ______ (C) ______ as File:
                for Rec in Records:
                    ______ (D) ______
            print("Update successful!")
        else:
            print("Record not found.")

    except FileNotFoundError:
        print("File not found.")

Questions:

(A) Write the complete open statement with appropriate file mode for Blank (A) that allows reading a binary file.

(B) Provide the method call for Blank (B) to read and deserialize a single record from the file object File.

(C) Write the complete 'open' statement with appropriate file mode for Blank (C) that allows writing the updated data into the binary file.

(D) Write the code for Blank (D) to write the updated record Rec into the file object File.

Show answer & explanation

(A) Open statement for reading binary file:
with open("directory.dat", "rb")
Reason: "rb" mode is used to read binary files.

(B) Method to read and deserialize record:
pickle.load(File)
Reason: pickle.load() reads one object (record) from the binary file and deserializes it.

(C) Open statement for writing updated data:
with open("directory.dat", "wb")
Reason: The "wb" mode opens the binary file in write mode and overwrites it with updated data.

(D) Code to write updated record:
pickle.dump(Rec, File)
Reason: pickle.dump() serializes the updated record Rec and writes it into the file.

Explore the full course: Hpsc Pgt Computer Science