我的Python代码无法将多个数据流保存到存储文件中

时间:2015-12-21 14:04:57

标签: python dictionary pickle

问题定义

创建您自己的命令行地址簿程序,使用该程序可以浏览,添加,修改,删除或搜索您的联系人,如朋友,家人和同事,以及他们的信息,如电子邮件地址和/或电话号码。必须存储详细信息以供日后检索。

基于上述问题描述,我能够开发出以下程序,

我目前面临的挑战是;
1.只有一个联系人保存到本地存储,旧联系人始终被覆盖。我希望对象的每个实例都保存不同的联系人到同一个文件(phonelist)
2. contact_del方法通过错误,虽然它做了它应该做的事情,有人可以告诉我这部分代码有什么问题,为什么我得到错误。最后我希望该错误被抑制。

import pickle
#   Declare the Class
class phone_book:
    def __init__(self):
        """ Initialize The Phone Book"""
        print('This is a command Line phone Book Directory')


    def add_detail(self):
        """ Detail of our Contacts is being collected"""
        address_book = {}
        address_value = []

        #   Accepting Value from the User
        print('Let add our friends Details')
        address_name = input('Enter name : ')
        address_phone = int(input('Enter phone Number : '))
        address_email = input('enter email : ')
        addess_Gtype = input('Specify Contact Group Type : ')
        address_value.append(address_phone)
        address_value.append(address_email)
        address_value.append(addess_Gtype)

        for i in address_value:
            address_book[address_name] = address_value
            #   Sending our Data to Permanent Storage
            with open("phonelist.txt", "wb") as myFile:
                pickle._dump(address_book, myFile)

    # Declare Function that will enable us to modify the data enter
    @classmethod
    def detail_modify(cls):
        """ We are Modifying our old friends Details"""
        modify_contact = input('Enter the Name of the to modify : ')
        with open("phonelist.txt", "rb") as myFile:
            address_book = pickle._load(myFile)
            # Iterate over the supply name
            for name, name_detail in address_book.items():
                if modify_contact not in name:
                    print('The contact does not exist')
                else:
                    print('We are ready to modify  Mr :', name)
                    address_phone = int(input('Enter phone Number : '))
                    address_email = input('enter email : ')
                    addess_Gtype = input('Specify Contact Group Type : ')
                    name_detail[0] = address_phone
                    name_detail[1] = address_email
                    name_detail[2] = addess_Gtype

                    # Finally we updating the Details enter
                    for i in name_detail:
                        address_book[name] = name_detail
                        #   Sending our Data to Permanent Storage
                        with open("phonelist.txt", "wb") as myFile:
                            pickle._dump(address_book, myFile)

    # Declare a function that Search for Keywords in the directory
    @classmethod
    def phone_search(cls):
        """ Return Contact Details based on the Keyword Enter"""
        keyword = input('Enter word you are searching for : ')
        with open("phonelist.txt", "rb") as myFile:
            address_book = pickle._load(myFile)


        #   Iteration over the received data from the storage
        for name, name_detail in address_book.items():
            if keyword in name or name_detail:
                print(address_book)

            else:
                print("Keyword not Found")

    # Were are removing people we are no more in friendship with
    @classmethod
    def contact_del(cls):
        """ We are deleting Contact we are done with friendship"""
        with open("phonelist.txt", "rb") as myFile:
            address_book = pickle._load(myFile)
        contact_remove = input('Enter name of Contact to Removed : ')
        for name, name_detail in address_book.items():
            if contact_remove == name:
                del address_book[contact_remove]
                print(contact_remove, 'Successfully removed')
            # Updating Our Storage again
            with open("phonelist.txt", "wb") as myFile:
                pickle._dump(address_book, myFile)
            else:
                print('Name Supply is not valid')

    # Sending the number of Phone contact to output Screen
    @classmethod
    def contact_view(cls):
        """ Displaying Our contacts Details"""
        with open("phonelist.txt", "rb") as myFile:
            address_book = pickle._load(myFile)
        print(address_book, 'Number of Contacts ',  len(address_book))

# Running below instance of object only retain last object the first
phone_book.contact_view()
contact1 = phone_book()
contact1.add_detail()
contact2 = phone_book()
contact2.add_detail()
phone_book.contact_view()
phone_book.phone_search()
phone_book.contact_del()

尽管上面的错误被调用的方法(phone_book.contact_del())删除了预期的用户,请参阅下面的phone_book.contact_del()输出

1 个答案:

答案 0 :(得分:1)

  

旧联系人总是被覆盖。

您正在打开'写' mode,它将覆盖任何具有相同名称的文件。你需要使用'追加'模式。将open("phonelist.txt", "wb")更改为open("phonelist.txt", "ab")请参阅this documentation,特别是有关mode参数的部分。

  

contact_del方法通过错误虽然它做了它应该做的事情

问题在于:

for name, name_detail in address_book.items():
    if contact_remove == name:
        del address_book[contact_remove]  # Don't do this

您正在迭代其中的值时修改字典,这会导致RuntimeError: dictionary changed size during iteration。通常,在for循环中时不要更改字典(或列表!)。修改迭代它们的循环内部的数据结构可能会导致意外错误。

在你的情况下,一个简单的if语句就足够了:

# Check if the requested contact is in the address book
if contact_remove in address_book:
    del address_book[contact_remove]