each record in binary files is stored like this
import pickle
student={}
def add():
n=int(input("enter number of entries"))
for i in range(n):
name=input("enter names")
marks=eval(input("enter marks"))
student[name]=marks
f=open("sample.dat","wb")
pickle.dump(student,f)
f.close()
if want to delete a specific record with name=<"some name"> how to do it
i tried like this but its not correct
def delete():
x=input("enter name to be deleted")
for i in student:
if x==i:
del student[x]
else:
print("name not found")
First of, a couple of improvements
del
an element of student
while you iterate over it. This is an error, while iterating over a dictionary you should not modify its keys.x
is in the dictionary is sufficient. You can do that with if x in students:
.For everything else, I have to guess, because your question is not specific enough.
I guess that you expect that when you call the delete()
function that the file content changes. But the delete() function does not write to any file, so maybe you forgot saving the new student
dictionary to the file?
Just a wild guess:
def delete():
x=input("enter name to be deleted")
if x in student:
del student[x]
else:
print("name not found")
with open("sample.dat","wb") as f:
pickle.dump(student,f)
You can not modify the contents of dictionary while iterating over it.
What you can do though is iterate over an array of keys of dictionary and delete items from dictionary if it matches.
ie change your delete function to:
def delete():
x=input("enter name to be deleted")
for key in list(dict.keys(student)):
if key==x:
print('matched')
del student[key]
import pickle
def delete():
f = open('bin.dat', 'rb+')
n=int(input('Enter roll no. which you want to delete:'))
i=[]
v=[]
flag=0
try:
while True:
i = pickle.load(f)
v.append(i)
if i[0]==n:
v.remove(i)
print("successfully deleted!!!!!!")
flag=1
except Exception:
if flag==0:
print("record not found")
f.close()
with open("bin.dat",'wb') as g:
for i in range(len(v)):
pickle.dump(v[i],g)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.