简体   繁体   English

从 python 中的二进制文件中删除特定记录

[英]deleting a specific record from a binary file in python

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如果要删除 name=<"some name"> 的特定记录,该怎么做

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首先,一些改进

  1. In your code you del an element of student while you iterate over it.在您的代码中,您在迭代它时del了一个student元素。 This is an error, while iterating over a dictionary you should not modify its keys.这是一个错误,在迭代字典时,您不应修改其键。
    For more information, read this:有关更多信息,请阅读以下内容:
    https://www.geeksforgeeks.org/python-delete-items-from-dictionary-while-iterating/ https://www.geeksforgeeks.org/python-delete-items-from-dictionary-while-iterating/
  2. You don't need to iterate over the dictionary at all.您根本不需要遍历字典。 Dictionary keys are unique, so checking if x is in the dictionary is sufficient.字典键是唯一的,因此检查x是否在字典中就足够了。 You can do that with if x in students: .你可以用if x in students:来做到这一点。
  3. Don't explicitely close file descriptors.不要明确关闭文件描述符。 Use context managers instead.请改用上下文管理器
    Like here: https://cmdlinetips.com/2016/01/opening-a-file-in-python-using-with-statement/喜欢这里: https://cmdlinetips.com/2016/01/opening-a-file-in-python-using-with-statement/

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.您希望当您调用delete() function 时文件内容会发生变化。 But the delete() function does not write to any file, so maybe you forgot saving the new student dictionary to the file?但是 delete() function 没有写入任何文件,所以也许您忘记将新的student词典保存到文件中?

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:即将删除的 function 更改为:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM