我正在制作通讯录,但遇到了问题。告诉我,str和list有问题。我是python的新手,所以我真的不知道该怎么做。 这是完整的程序:
print("\n This is your address book.")
import os
import time
saveFile = open("ContactList.txt", "r")
ContactsString = saveFile.read()
saveFile.close()
Contacts = ContactsString.split('\n')
while '' in Contacts:
Contacts.remove('')
def printContacts():
index = 1
for contact in Contacts:
print("{}: {}".format(index, contact))
index = index + 1
def addContact():
print("You have chosen to add a new contact into your address book.")
name = input("What's the contacts name? ")
counter = Contacts.count(name)
if counter == 0:
address = input("Enter the address of " + name + ': ')
email = input("Enter the email of " + name + ': ')
Contacts.append([ name, address, email ])
else:
print("The contact already exists in the address book.")
print("If you desire to change the contacts current information, enter nr 3 in the menu.")
def browseContacts():
print("You have chosen to view all your contacts with their name, address and email." "\n")
for i in range(0, len(Contacts), 3):
print(Contacts[i], Contacts[i + 1], Contacts[i + 2], '\n')
def searchContacts():
print("\n You have chosen to search up a specific contact.")
searchName = input("Enter the name of the contact that you want to search up: ")
searchFound = False
for i in range(0, len(Contacts), 3):
if searchName == Contacts[i]:
searchName = True
break
if searchFound == True:
print(Contacts[i], Contacts[i + 1], Contacts[i + 2], "\n")
else:
print("We couldn't find " + searchName + " in the address book.")
print("Check whether your spelling was correct or not.")
time.sleep(4)
def deleteContact():
print('\n You have chosen option 4, to delete a specific contact from your address book')
printContacts()
deletename = input(' Enter the name of the contact you wish to delete from your address book: ').title()
deletefound = False
for i in range(0, len(Contacts), 3): #finds the contact the user wants to delete. It only iterates through each third post so that it only goes through the names of the contact.
if deletename == Contacts[i]:
deletefound = True
break
if deletefound == True:
Contacts.pop(i) # deletes the contact information from the list
Contacts.pop(i)
Contacts.pop(i)
print('\n ' + deletename + 'has been removed from your address book')
else:
print('\n ' + deletename + "doesn't exist in the address book")
def modifyContacts():
print("You have chosen option 5, to update a specific contact in your address book.")
printContacts()
newName = input("Enter the name of the contact you wish to update: ")
modifyFound = False
for i in range(0, len(Contacts), 3):
if newName == Contacts[i]:
modifyFound = True
break
if modifyFound == True:
Contacts[i] = input(' Enter the new name of ' + newName + ': ')
Contacts[i + 1] = input(' Enter the new address of ' + Contacts[i] + ': ')
Contacts[i + 2] = input(' Enter the new e-mail of ' + Contacts[i] + ': ')
print('\n The contact has now been updated')
else:
print("\n " + newName + " doesn't exist in the address book")
print(" You can add " + newName + "to your address book by pressing 1 in the menu below")
time.sleep(4)
running = True
while running == True:
print('''
===================================================================
Menu:
1: Add new contact (press 1)
2: Show all contacts (press 2)
3: Show a specific contact (press 3)
4: Delete contact (press 4)
5: Update contact (press 5)
6: Quit program (press 6)
===================================================================''')
actionchoice = input('\n Please enter your choice of action: ')
if actionchoice == '1':
addContact()
elif actionchoice == '2':
browseContacts()
elif actionchoice == '3':
searchContacts()
elif actionchoice == '4':
deleteContact()
elif actionchoice == '5':
modifyContacts()
elif actionchoice == '6':
print('\n Shutting down. Thank you for using the adressbook! \n')
running = False
else:
print('\n The entered command does not exist within this program')
print(' Please enter one of the actions shown in the menu: \n')
time.sleep(4)
saveFile = open("ContactList.txt", "w")
for x in range(0, len(Contacts), 3):
saveFile.write("\n" + Contacts[x] + "\n")
saveFile.write( Contacts[x + 1] + "\n")
saveFile.write( Contacts[x + 2] + "\n")
saveFile.close()
问题到最后,问题说:
Exception has occurred: TypeError
**can only concatenate str (not "list") to str**
File "C:\Users\Anvandare\Documents\Programmering1\Arbetet\addressbook.py", line 162, in <module>
saveFile.write("\n" + Contacts[x] + "\n")
换句话说,这就是问题所在
saveFile.write("\n" + Contacts[x] + "\n")
我应该怎么做才能工作?
答案 0 :(得分:0)
此行是错误的:
Contacts.append([ name, address, email ])
这不是将每个变量附加为列表的单独元素,而是在Contacts
中创建嵌套列表。应该是:
Contacts.append(name)
Contacts.append(address)
Contacts.append(email)
或:
Concacts += [ name, address, email ]
您还需要修复printContacts()
才能像其他代码一样,以3组为一组来处理Contacts
。
def printContacts():
index = 1
for i in range(0, len(Contacts), 3):
print("{}: {} {} {}".format(index, *Contacts[i:i+3]))
index = index + 1
恕我直言,Contacts
最好是字典列表,但是这样做将需要重写90%的代码,而我在这里不打算这样做。