Python通讯录TXT文件删除功能无报错但未生效问题求助
解决通讯录程序删除功能失效的问题
嘿,我仔细瞅了下你的代码,发现几个关键问题导致删除功能没生效,咱们一步步来修复:
1. 最致命的错误:文件名写错了!
在delete_contact函数的最后,你写入修改后内容的时候用了"FileName"作为目标文件名,而不是实际存储数据的"DATA.txt"!这就导致你做的替换操作完全没作用到正确的文件上,原文件自然纹丝不动。
2. 其他需要优化的小问题
- 文件关闭的写法错误:你写了
file.close但少了括号,应该是file.close(),不过其实用with语句管理文件的话,文件会自动关闭,完全不需要手动调用close,建议把那些手动close的代码删掉,更简洁安全。 - 匹配逻辑不够友好:当前要求用户复制整个联系人的内容(包括格式)来删除,很容易因为换行、空格输错导致匹配失败。不如改成让用户输入联系人名字,自动定位并删除对应的联系人块,体验更好。
修复后的完整代码
import os, time, random, sys, pyautogui # function for creating a new contact. def new_contact(): name = str(input("Clients name?\n:")) name = name + " -" info = str(input("Info about the client?\n:")) # starts formatting clients name and info for injection into file. total = "\n\n" + name + " " + info + "\n" # Injects info into file. with open("DATA.txt", "a") as file: file.write(total) main() # function for listing ALL contacts made. def list_contacts(): # 把函数名从list改成list_contacts,避免和内置函数冲突 with open("DATA.txt", "r") as file: read = file.read() # detects whether there are any contacts at all. If there are none the only str in the file is "Clients:" if read == "Clients:": op = str(input("You haven't made any contacts yet..\nDo you wish to make one?\n:")) if op.lower() == "y": new_contact() else: main() else: print(read) os.system('pause') main() # Function for deleting contact def delete_contact(): with open("DATA.txt", "r") as file: read = file.read() # detects whether there are any contacts at all. If there are none the only str in the file is "Clients:" if read == "Clients:": op = str(input("You haven't made any contacts yet..\nDo you wish to make one?\n:")) if op.lower() == "y": new_contact() else: main() else: print(read, "\n") # 改成让用户输入联系人名字,更友好 target_name = input("Enter the client name you wish to delete\n:") # 拆分文件内容,找到对应的联系人块 lines = read.split("\n\n") new_content = [] for block in lines: # 检查当前块是否包含目标名字(排除开头的"Clients:") if block.strip() != "Clients:" and target_name not in block: new_content.append(block) # 重新拼接内容,保持格式 updated_content = "\n\n".join(new_content) # 写入正确的文件! with open("DATA.txt", "w") as file: file.write(updated_content) print(f"Contact '{target_name}' has been deleted successfully!") main() # Main Menu Basically. def main(): list_contacts_input = str(input("List contacts? - L\n\nMake a new contact - N\n\nDelete a contact? - D\n:")) if list_contacts_input.lower() in ("l"): list_contacts() elif list_contacts_input.lower() in ("n"): new_contact() elif list_contacts_input.lower() in ("d"): delete_contact() else: print("Invalid input, please try again!") main() # 初始化DATA.txt(如果不存在的话) if not os.path.exists("DATA.txt"): with open("DATA.txt", "w") as file: file.write("Clients:") main()
额外的优化点说明
- 把原函数名
list改成了list_contacts,避免和Python内置的list函数重名,防止潜在冲突。 - 增加了对
DATA.txt的初始化逻辑,如果文件不存在会自动创建并写入初始的Clients:内容。 - 用
lower()统一处理用户输入的大小写,不管用户输入L/l、N/n、D/d都能识别,更健壮。 - 删除功能改成按名字匹配,用户不用复制整段内容,操作更简单。
内容的提问来源于stack exchange,提问作者HomeMadeMusic
相关产品推荐
相关产品推荐

