Pickle文件包含多个对象

2024-05-16 08:56:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法使文件存储多个联系人实例。添加新联系人并尝试打印后,出现“IndexError:list index out of range”错误。我该怎么做才能使它工作呢?你知道吗

import pickle

class People():
    def __init__(self, name, surname, age, mobile_no, home_no):
        self.name = name
        self.surname = surname
        self.age = age
        self.mobile_no = mobile_no
        self.home_no = home_no

    def DisplayContacts(self):
        print("First Name: \t", self.name)
        print("Surname: \t", self.surname)
        print("Age: \t", self.age)
        print("Mobile Number: \t", self.mobile_no)
        print("Home Number: \t", self.home_no)
        print()


def addContact():
    newname = str(input("First name: \t"))
    newsurname = str(input("Surname: \t"))
    newage = int(input("Age: \t"))
    newmobile_no = int(input("Mobile Number: \t"))
    newhome_no = int(input("Home Number: \t"))
    newContact = People(newname, newsurname, newage, newmobile_no, newhome_no) 
    return newContact

cont = 1

contacts = []


while cont == 1:
    user = input("Do you want to add contact? (Y/N)")
    if user == "Y" or user == "y":
        print ("works")
        contacts.append(addContact())
        file = open("CList.pickle", "ab")
        pickle.dump(contacts, file, pickle.HIGHEST_PROTOCOL)
        file.close()
    else:
        print ("111")
        cont = 0


useropen = input("open file? (Y/N)")
if useropen == "Y" or useropen == "y":


    with open ("CList.pickle", "rb") as pickled_file:
        contacts = pickle.load(pickled_file)
        print(contacts[0].surname)
        print(contacts[1].surname)


else:
    print("Null") 

Tags: nonameselfnumberhomeinputagedef
1条回答
网友
1楼 · 发布于 2024-05-16 08:56:11

简单地将拾取的对象附加到文件与拾取列表是不同的。每次追加时,都会创建另一个pickle记录。多次读取文件以获取列表:

with open ("CList.pickle", "rb") as pickled_file:
    contacts = []
    try:
        while True:
            contacts.append(pickle.load(pickled_file))
    except EOFError:
            pass

现在,不必附加联系人列表(这将为您提供一个包含许多重复项的列表),只需pickle新联系人:

with open("CList.pickle", "ab") as _file:
    while True:
        user = input("Do you want to add contact? (Y/N)")
        if user == "Y" or user == "y":
            print ("works")
            pickle.dump(addContact(), _file, pickle.HIGHEST_PROTOCOL)
        else:
            print ("111")
            break

相关问题 更多 >