我正在通过python开发一个非常简单的联系人程序。我们刚刚开始尝试try和except语句。在将try和except语句引入我的各种函数之前,我的list函数(包括在下面)运行良好。我在csv文件中没有联系人的情况下向列表函数添加了一条错误消息。由于这样做,我无法显示新添加的(在新创建的csv文件中)。实际上,当我键入命令列出联系人时,我什么也没得到。光标只是坐着并闪烁,没有结果,没有错误信息,什么也没有。关于如何解决此问题的任何想法?
代码:
def readContacts():
while True:
try:
contacts = []
with open(CONTACTS_FILE, newline="") as conFile:
reader = csv.reader(conFile)
for row in reader:
contacts.append(row)
except FileNotFoundError:
print()
print("Could not find contacts file!")
print("Starting new contacts file...")
print()
break
writeContacts(contacts)
return contacts
def writeContacts(contacts):
with open(CONTACTS_FILE, "w", newline="") as conFile:
writer = csv.writer(conFile)
writer.writerows(contacts)
def addContacts(contacts):
name = input("Name: ")
email = input("Email: ")
phone = input("Phone: ")
addRow = []
addRow.append(name)
addRow.append(email)
addRow.append(phone)
contacts.append(addRow)
writeContacts(contacts)
print(name + " was added.")
print()
def viewContacts(contacts):
while True:
try:
num = int(input("Number: "))
if num > len(contacts):
print("Invalid contact number.")
else:
col = contacts[num - 1]
print("Name: " + str(col[0]))
print("Email: " + str(col[1]))
print("Phone: " + str(col[2]))
except ValueError:
print("Invalid integer.")
break
print()
#function to allow user to list contact names from csv file
def listContacts(contacts):
while True:
if len(contacts) == 0:
print("There are no contacts in the list.")
break
else:
for i in range(len(contacts)):
row = contacts[i]
readContacts()
print(str(i + 1) + "." + str(row[0]))
print()