def modifyContact():
displayName = input('Enter a Name to search for:\n ')
afile = open('contacts.txt', 'r+')
addressList = afile.readlines()
#Using the in function to see
for ch in addressList:
if displayName in ch:
print(ch)
nameRemove = input('What do you want to replace?')
nameModify = input('What did you want to replace it with')
for ch in addressList:
if ch == nameRemove:
del addressList[ch]
addressList.append(nameModify)
afile.write(str(addressList))
afile.close()
break
def DeleteContact():
deleteName = input('Who do you want to delete?')
afile = open('contacts.txt', 'a+')
deleteList = afile.readlines()
for ch in deleteList:
if ch in deleteName:
deleteList.remove(ch)
afile.write(str(deleteList))
afile.close()
break
**当我运行我的代码时,修改功能没有修改列表中的联系人,删除功能正在删除整个文档,而不是删除联系人**
答案 0 :(得分:0)
对于修改部分,您不是替换列表中的联系人,而是附加到该联系人
使用:addressList[addressList.index(ch)] = nameModify
替换列表中的项目。
对于删除部分,您在附加模式下打开文件,因此列表内容将在末尾附加。
afile.write(str(list))
也会将内容写为['item1', 'item2']
,这可能不是您想要的格式。
如果您希望将列表中的每个元素写入文件,您可以使用' map'
map(afile.write,addressList)
def modifyContacts():
displayName = input('Enter a Name to search for:\n ')
afile = open('contacts.txt', 'r+')
addressList = afile.readlines()
#Using the in function to see
for ch in addressList:
if displayName in ch:
print(ch)
nameRemove = input('What do you want to replace?')
nameModify = input('What did you want to replace it with')
print(addressList)
print(nameRemove)
for ch in addressList:
if ch[:-1] == nameRemove:
addressList[addressList.index(ch)] = nameModify
print(addressList)
break
afile = open('contacts.txt', 'w+')
map(afile.write, addressList)
afile.close()
def deleteContacts():
deleteName = input('Who do you want to delete?')
afile = open('contacts.txt', 'r+')
deleteList = afile.readlines()
print deleteList
for ch in deleteList:
if ch[:-1] in deleteName:
deleteList.remove(ch)
print deleteList
break
afile=open('contacts.txt', 'w+')
map(afile.write, deleteList)
afile.close()