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')
So if my text file have two same words:
name | priority
gun | low
granade | high
gun | high
and I put that I want to delete:
name: gun
priority: high
The second gun on the list, there should be the only thing that is deleting
When I delete, the file only deletes the ones that have just priority of high:
name | priority
gun | low
I want the file like this:
name | priority
gun | low
grenade | high
Essentially, you want skip lines with the name
and priority
words in them i.e. (A and B)
, or to put it conversely not (A and B)
which is equal to (not A) or (not B)
✶, i.e. in order to keep those without name
in the line or those that do have it, but don't have the priority
word in them, . Here's how to write code that does that (using the latter logic to decide when to write copy lines). I also streamlined the code in your question somewhat by using with
to open both the files simultaneously — so their closing will be done automatically. I also removed the unneeded os.remove()
.
✶De Morgan’s transformation rules of logic.
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')