Python通讯录删除功能实现求助:添加功能已完成,删除遇阻
Python通讯录删除功能问题修复
原代码存在的问题:
- 行内容匹配错误:读取的每行格式是
姓名 号码\n,直接和输入的姓名(仅姓名)比较永远不相等,需要拆分每行提取姓名后再匹配。 - 索引计算逻辑混乱:counter的递增条件错误,导致删除的索引位置不对。
- 未同步修改到文件:删除列表元素后没有将新内容写回文件,操作不会生效。
- 无异常处理:找不到目标联系人时,会错误删除最后一行数据。
- 函数定义位置不当:
add和delete函数放在while循环内部,每次循环都会重新定义,完全没必要。
修正后的完整代码:
def add(): # 移到循环外定义 with open("filename.txt", "a") as file: # 用with自动关闭文件更安全 name1 = input("Enter Contact Name\n").capitalize() number1 = input("Enter Contact Number\n") file.write(f"{name1} {number1}\n") def delete(): deleted_contact = input("Enter the name you want to delete from the Contact list : ").capitalize() lines = [] found = False # 读取文件并筛选保留非目标联系人 with open("filename.txt", "r") as file: for line in file: line = line.strip() # 去掉换行符和首尾空格 if not line: # 跳过空行 continue name, _ = line.split(maxsplit=1) # 拆分姓名和号码,只取姓名 if name != deleted_contact: lines.append(line + "\n") # 保留原格式(加回换行符) else: found = True # 将筛选后的内容写回文件 if found: with open("filename.txt", "w") as file: file.writelines(lines) print(f"联系人 {deleted_contact} 已删除") else: print(f"未找到联系人 {deleted_contact}") while True: choice = input(""" Type '1' to add Contact Type '2' to delete contact Type '3' to show all contacts Type '4' to Enter Statistical report menu Type 'exit' to exit \n""") # Menu/options if choice == "1": add() elif choice == "2": delete() elif choice == "3": # 补充显示所有联系人的功能 with open("filename.txt", "r") as file: print("\n所有联系人:") for line in file: print(line.strip()) elif choice.lower() == "exit": print("退出程序") break
关键修正说明:
- 把函数移到
while循环外部,避免重复定义。 - 使用
with语句操作文件,自动处理文件关闭,更安全。 - 删除逻辑改为筛选保留法:遍历所有行,只保留非目标联系人的行,再写回文件,比通过索引删除更直观且不易出错。
- 增加了联系人存在性判断,找不到时提示用户,避免误删。
- 补充了
show all contacts的功能实现(原菜单有选项但无对应逻辑)。 - 修正了菜单里的拼写错误
Stiatical为Statistical。
内容的提问来源于stack exchange,提问作者momoshki
相关产品推荐
相关产品推荐

