def deletematerial(): print('Deleting of material ') fh_r = open("AQUESTO.txt", "r") name = input('Enter the name of de material to eliminate: ').lower() priority = input('the material is of low or high: ') print("\n") with open("bb.txt", "w") as output: for line in fh_r: if (name and priority not in line.strip("\n")): output.write(line) fh_r.close() os.remove("AQUESTO.txt") os.replace('bb.txt', 'AQUESTO.txt')
所以如果我的文本文件有两个相同的词:
name | priority gun | low granade | high gun | high
我把我想删除的:
name: gun priority: high
名单上的第二把枪,应该是唯一被删的
当我删除时,该文件仅删除具有高优先级的文件:
name | priority gun | low
我想要这样的文件:
name | priority gun | low grenade | high
本质上,您希望跳过其中包含nameandpriority单词的行 ie (A and B),或者反过来说它not (A and B)等于(not A) or (not B)✶,即为了保留那些没有name在行中或那些确实有它但没有priority单词 in他们, 。以下是如何编写执行此操作的代码(使用后一种逻辑来决定何时编写复制行)。我还通过使用同时with打开两个文件来简化您问题中的代码- 因此它们的关闭将自动完成。我还删除了不需要的.os.remove()
name
priority
(A and B)
not (A and B)
(not A) or (not B)
with
os.remove()
✶德摩根的逻辑转换规则。
import os def delete_material(): print('Deleting of material ') name = input('Enter the name of the material to eliminate: ').lower() priority = input('the material is of low or high: ').lower() print("\n") with open("AQUESTO.txt", "r") as fh_r, open("bb.txt", "w") as output: for line in fh_r: if name not in line or priority not in line: output.write(line) os.replace('bb.txt', 'AQUESTO.txt') # Replace original file with updated version. delete_material() print('fini')