#python
#python
Вопрос:
Мне нужно добавить обработку исключений в эту программу. Если программа не может найти CSV-файл, она должна отобразить соответствующее сообщение и создать новый CSV-файл, который не содержит никаких контактных данных. Для команд просмотра и удаления отобразите соответствующее сообщение об ошибке, если пользователь вводит недопустимое целое число или неверный контактный номер.
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()
Комментарии:
1. У вас есть вопрос?
Ответ №1:
Вы могли бы просто открыть файл в режиме добавления, который создаст файл, если он не существует.
except FileNotFoundError as e:
print("Could not find " FILENAME " file.")
f=open(FILENAME, "a")
# the value of contacts would be [] here
return []