【问题标题】:Is there a way to remove a whole line in a text file if the word is found in python如果在python中找到单词,有没有办法删除文本文件中的整行
【发布时间】:2023-03-08 19:04:01
【问题描述】:

基本上我需要它来查找用户输入和包含该单词的行以删除整行。我不知道该怎么做并且被卡住了。我可以帮忙吗

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)

是的,我知道这段代码现在真的坏了,所以我需要帮助!

【问题讨论】:

  • 了解strip() 的作用,然后改用replace()(或者更好的if needle not in haystack:

标签: python text


【解决方案1】:

使用条件检查itemRemove 是否在line

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

【讨论】:

  • 成功了,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
  • 2019-07-08
相关资源
最近更新 更多