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
या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
