A Binary file, SONG.DAT has the following structure:
{SNO:[SNAME, SARTIST]}
Where
SNO – Song Number
SNAME – Song Name
SARTIST is Song Artist
Write a user defined function, deleteSong(sno), that accepts sno as parameter and deletes the record from the binary file SONG.DAT, that has the given song number.
Answer:
Answer by student
Detailed answer by teachoo
-lock-
- The question asks us to write a user defined function, deleteSong(sno), that accepts sno as parameter and deletes the record from a binary file SONG.DAT, that has the given song number.
-
To solve this problem, we need to perform the following steps:
- Import the pickle module using import statement. This module allows us to read and write binary data to and from files.
-
Define our function, deleteSong(sno), using
def
statement. The function takes one parameter, sno, which is the song number to delete.
- Open the file SONG.DAT in read mode using open() function with “rb” as the mode argument. This will allow us to read binary data from the file.
- Create an empty list to store the remaining records. We will use this list to write back to the file later.
-
Loop through each record in the file using a
try-except
block. We will use a
while
loop with
True
as condition and break when we encounter an
EOFError
, which indicates that we have reached the end of file.
- Load each record from the file using pickle.load() function. This will return a dictionary with keys “SNO”, “SNAME” and “SARTIST” and values as song number, name and artist respectively.
- Get the song number from the dictionary by indexing. The song number is at key “SNO”.
- Check if the song number does not match our parameter using != operator. If yes, then append this dictionary to our records list. If no, then skip this dictionary as we want to delete it.
- Close our file using close() method. This will free up any resources used by our file object.
- Open our file again in write mode using open() function with “wb” as mode argument. This will allow us to write binary data to our file. Note that this will overwrite any existing data in our file, so we need to make sure that we have stored all the remaining records in our records list before doing this step.
-
Loop through each record in our records list using another
for
loop.
- Dump each record to our file using pickle.dump() function. This will write the dictionary as binary data to our file.
- Close our file again using close() method.
- End our function definition using an empty line.
- Here is the code that implements these steps in Python:
-endlock-