簡體   English   中英

如果在 python 中找到該單詞,是否有辦法刪除文本文件中的整行

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

基本上我需要這個來找到用戶輸入和包含該單詞的那一行來刪除整行。 我不知道該怎么做並且被卡住了。 我可以幫忙嗎

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)

是的,我知道這段代碼現在真的壞了,這就是我需要幫助的原因!

使用條件檢查itemRemove是否line

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM