English

Write a program to delete the content provided by user from the binary file. The file is very large and can't fit in computers memory.

Advertisements
Advertisements

Question

Write a program to delete the content provided by user from the binary file. The file is very large and can't fit in computers memory.

Code Writing
Advertisements

Solution

The original file is processed record by record, so the complete file is never loaded into memory.

import os
import pickle

def delete_from_binary(filename, unwanted_value):
    temporary = filename + ".tmp"

    with open(filename, "rb") as source, open(temporary, "wb") as target:
        try:
            while True:
                record = pickle.load(source)
                if record != unwanted_value:
                    pickle.dump(record, target)
        except EOFError:
            pass

    os.replace(temporary, filename)

value = input("Enter content to delete: ")
delete_from_binary("data.dat", value)

If the binary file contains integers or dictionaries, convert the user input to the same type before comparison.

shaalaa.com
  Is there an error in this question or solution?
Chapter 7: Data File Handling - EXERCISE [Page 146]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 7 Data File Handling
EXERCISE | Q 16. | Page 146
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×