Search code examples
pythontext

Is there a way to remove a whole line in a text file if the word is found in python


Basically I need this to find the users input and that line which contains that word to delete the whole line. I have no idea what to do and am stuck. May I have some help

def delStock(f):
    count = 0
    itemRemove = input("""
Please enter the item you wish to delete.
: """)
    with open("CurrentStock.txt", "r") as f:
        lines = f.readlines()
    with open('CurrentStock.txt', "w") as f:
        for line in lines:
            if line.strip(itemRemove) != itemRemove:
                f.write(line)

Yes I know this code is really broken right now thats why I need help!


Solution

  • Use a condition to check if itemRemove is in line or not

    with open('CurrentStock.txt', "w") as f:
        for line in lines:
            if itemRemove not in line:
                f.write(line)