मराठी

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

प्रश्न

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

उत्तर

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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 7: Data File Handling - EXERCISE [पृष्ठ १४६]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
पाठ 7 Data File Handling
EXERCISE | Q 16. | पृष्ठ १४६
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×