与许多对象的泡菜文件

时间:2014-06-19 19:34:46

标签: python pickle

我无法让我的文件存储多个联系人实例。添加新联系人并尝试打印后,它会出现" IndexError:列表索引超出范围"错误。我该怎么做才能使它发挥作用?

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") 

1 个答案:

答案 0 :(得分:1)

简单地将拾取的对象附加到文件与挑选列表不同。 EAch你追加的时间,你创造了另一个腌制记录。多次阅读该文件以获取列表:

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

现在,不是附加联系人列表(这会给你一个包含许多重复项的列表的列表),而只是挑选新的联系人:

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