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
**当我运行代码时,modify函数不是修改列表中的联系人,delete函数是删除整个文档,而不是contact**
对于“修改部分”,您不会替换列表中的联系人,而是将其追加到列表中。
使用:
addressList[addressList.index(ch)] = nameModify
替换列表中的项对于删除部分,您以附加模式打开了文件,因此列表内容将附加在末尾
而且
afile.write(str(list))
会将内容写成['item1', 'item2']
,这可能不是您想要的格式。 如果要将列表中的每个元素写入文件,可以使用“map”映射(afile.write,addressList)
相关问题 更多 >
编程相关推荐