简体   繁体   中英

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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM