处理lis列表的函数问题

2024-05-19 11:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

修改联系人

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**


Tags: toinyouforinputifdef联系人
1条回答
网友
1楼 · 发布于 2024-05-19 11:30:47

对于“修改部分”,您不会替换列表中的联系人,而是将其追加到列表中。
使用:addressList[addressList.index(ch)] = nameModify替换列表中的项

对于删除部分,您以附加模式打开了文件,因此列表内容将附加在末尾

而且afile.write(str(list))会将内容写成['item1', 'item2'],这可能不是您想要的格式。 如果要将列表中的每个元素写入文件,可以使用“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()   

相关问题 更多 >

    热门问题