如何编写函数以使用 pickle 从二进制文件中删除记录?

How do I write a function to delete a record from a binary file using pickle?

我正在以列表的形式存储记录。

Write a menu driven program to append, display and delete student details [id, name, percentage] in a binary file. Deletion should be done on the basis of student id.

所以我写了这个:

#Code to append display and delete student details
import pickle
def append():
    f = open("student.bin","ab")
    x = int(input("Enter number of students to be appended: "))
    for i in range(x):
        y = eval(input("Enter details in the form [id, name, percentage]: "))
        pickle.dump(y,f)
    f.close()

def display():
    f = open("student.bin","rb")
    while True:
        try:
            x = pickle.load(f)
            print(x)
        except EOFError:
            break
    f.close()

def delete():
    f = open("student.bin","ab+")
    x = input("Enter id to be deleted: ")
    y = pickle.load(f)
    for i in y:
        if str(i[0]) == str(x):

最后,我将用户输入与匹配的 ID 相匹配,但我不知道应该如何从二进制文件中完全删除列表。

这是一种方法:从文件中读取所有学生记录,删除我们要删除的记录,然后将整个列表写回文件。

def delete():
    student_id = int(input("Enter id to be deleted: "))
    records = []
    with open("student.bin", "rb") as stream:
        while True:
            try:
                record = pickle.load(stream)
                if record[0] != student_id:
                    records.append(record)
            except EOFError:
                break
    
    # records now contains all students, except for the one we want to delete
    with open("student.bin", "wb") as stream:
        for record in records:
            pickle.dump(record, stream)

另一种方法是打开 read/write 的文件并加载每条记录并将其写回。比较难理解。