如何删除文本中同时含两个指定字符串的行?Python代码修正
问题根因
原代码的核心错误出在匹配判断的逻辑上:if (name and priority not in line.strip("\n")) 受Python运算符优先级影响,实际执行逻辑是「只要输入的name非空,且当前行不包含输入的priority字符串就保留该行」,完全没有对name字段做匹配校验,才会导致所有带high的行都被误删。
除此之外直接对整行做包含匹配也不可靠,没有按照文件|分隔的格式拆分字段做精确比对,很容易出现误判。另外原代码还存在未导入os模块、冗余的文件删除操作、没有处理字段前后空格等小问题。
修正后可直接运行的代码
import os def deletematerial(): print('Deleting of material ') target_name = input('Enter the name of the material to eliminate: ').lower().strip() target_priority = input('the material is of low or high: ').lower().strip() print("\n") # 同时打开读写文件,自动管理文件句柄避免泄漏 with open("AQUESTO.txt", "r", encoding="utf-8") as read_f, open("bb.txt", "w", encoding="utf-8") as write_f: for line in read_f: line_content = line.rstrip("\n") # 跳过空行 if not line_content.strip(): continue # 按|拆分字段,统一去除前后空格、转小写做匹配 fields = [item.strip().lower() for item in line_content.split("|")] # 表头行直接写入保留 if fields[0] == "name" and fields[1] == "priority": write_f.write(line) continue current_name, current_pri = fields[0], fields[1] # 仅当名称、优先级同时匹配目标值时,跳过写入(即删除该条目),其余行全部保留 if not (current_name == target_name and current_pri == target_priority): write_f.write(line) # 直接用临时文件替换原文件即可,不需要先手动删除原文件 os.replace("bb.txt", "AQUESTO.txt")
运行后输入gun、high时,只会删除gun|high这一条记录,最终文件会保留表头、gun|low、granade|high三行,完全符合预期。
内容的提问来源于stack exchange,提问作者María Verónica Arismendi Pérez
相关产品推荐
相关产品推荐

