使用Python进行异常处理的Contact Manager

问题描述 投票:0回答:1

我需要为此程序添加异常处理。如果程序找不到CSV文件,它应显示相应的消息并创建一个不包含任何联系人数据的新CSV文件。对于view和delete命令,如果用户输入无效的整数或无效的联系号码,则显示相应的错误消息。

import csv
import sys

FILENAME = "contacts.csv"


def read_contacts():
    try:
        contacts = []
        with open(FILENAME, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                contacts.append(row)
        return contacts
    except FileNotFoundError as e:
       print("Could not find " + FILENAME + " file.")
       f=open(FILENAME, "w+")

       return contacts
    except Exception as e:
        print(type(e), e)
        exit_program()


def write_contacts(contacts):
    try:
        with open (FILENAME, "w", newline="") as file:
            writer = csv.writer(file)
            writer.writerows(contacts)

    except OSError as e:
        print(type(e), e)
        exit_program()
    except Exception as e:
        print(type(e), e)
        exit_program()


def list_contacts(contacts):
    try:
        for i in range(0, len(contacts)):
           contact = contacts[i]
           print(str(i+1) + ". " + contact[0]+ "(" + str(contact[1]) +")" )
           print()

    except:
        try:
            if len(contact) == 0:
               print("There are no contacts in the list.\n")
            else:
                print(type(e), e)
                return

        except:
           print(type(e), e)
           return

def view_contacts(contacts):
    while True:
        try:
            number = int(input("Number: "))


        except ValueError:
            print("Invalid integer. Please try again.")
            continue

    if number < 1 or number > len (contacts):
        print("Invalid contact number")
        print()
    else:


            contact = contacts[number-1]
            print("Name: " + contact[0])
            print("Email: " + contact[1])
            print("Phone: " + contact[2])
            print()


def add_contacts(contacts):
    name = input("Name: ")
    email = input("Email: ")
    phone = input("Phone: ")
    contact = []
    contact.append(name)
    contact.append(email)
    contact.append(phone)
    contacts.append(contact)
    write_contacts(contacts)
    print(name + " was added")
    print()


def delete_contacts(contacts):
    while True:
        try:
            number = int(input("Number: "))
        except ValueError:
            print("Invalid integer.")
            continue


        if number < 0 or number > len (contacts):
            print("invalid number")


        else:
           break
        contact = contacts.pop(number-1)
        write_contacts(contacts)
        print(contact[0] + " was deleted")


def display_menu():

    print("Contact Manager")
    print()
    print("COMMAND MENU")
    print("list - Display all contacts", "\nview - View a contact",
          "\nadd - Add a contact", "\ndel - Delete a contact",
          "\nexit - Exit program")

    print()

##definition main menu
def main():


    display_menu()
    contacts =  read_contacts()
    while True:
        command = input("Command: ")
        if command.lower() == "list":
            list_contacts(contacts)
        elif command.lower() == "view":
            view_contacts(contacts)
        elif command.lower() == "add":
            add_contacts(contacts)
        elif command.lower() == "del":
            delete_contacts(contacts)
        elif command.lower() == "exit":
            print("Good bye!")
            break
        else:
            print("Invalid command. Please try again.\n")

if __name__ == "__main__":
    main()
python
1个回答
0
投票

您可以使用追加模式打开文件,如果该文件不存在,将创建该文件。

except FileNotFoundError as e:
       print("Could not find " + FILENAME + " file.")
       f=open(FILENAME, "a")

       # the value of contacts would be [] here
       return []
© www.soinside.com 2019 - 2024. All rights reserved.