Python 如何根据用户输入从txt文件中删除特定行?

Python 如何根据用户输入从txt文件中删除特定行?,python,Python,如何删除基于用户输入的文本文件中的特定行 def remove(): delete_value = input("Enter the value you wish to delete: ") with open("values.txt", "r") as f: lines = f.readlines() with open("values.txt", "w"

如何删除基于用户输入的文本文件中的特定行

def remove():
    delete_value = input("Enter the value you wish to delete: ")

    with open("values.txt", "r") as f:
        lines = f.readlines()
    with open("values.txt", "w") as f:
        for line in lines:
            if line.strip("\n") != delete_animal:
                 f.write(line)
非常感谢您的帮助,谢谢

def remove():
    delete_value = input("Enter the value you wish to delete: ")

    with open("value.txt", "r") as f:
        file = f.readlines()
    with open("value.txt", "w") as f:
        for line in file:
            # we will skip the line that contains our target word
            # in this case the delete_animal
            words = line.strip("\n").lower().split(' ')
            if delete_value.lower() not in words:
                f.write(line)
输入文件:

line 1
line 2
line 3
line 4
may name is sudipto
my name is sudiptoandiloveprogramming

user input: sudipto
line 1
line 2
line 3
line 4
my name is sudiptoandiloveprogramming
删除后输出文件:

line 1
line 2
line 3
line 4
may name is sudipto
my name is sudiptoandiloveprogramming

user input: sudipto
line 1
line 2
line 3
line 4
my name is sudiptoandiloveprogramming
试试这个-

def remove():
    num = []
   
    delete_animal = input("Enter the name of the animal you wish to delete: ")
    file = open("txt file", "r")
    file.seek(0)
    list_of_lines = file.readlines()
    file.seek(0)
    lines = file.read().splitlines()
    file.close()
    if delete_animal not in lines:
        print("That line does not exist, please try again")
   

    for word in lines:
        num.append(0)
    
    if delete_animal == word:
        file = open('txt file','w')
        list_of_lines[len(num)-1] = ""
        file.writelines(list_of_lines)
        print('Animal Deleted')
这应该删除输入动物所在的行

编辑-

它应该是
A3\u s3902169\u stock.txt
。您需要添加扩展名
.txt

到目前为止您尝试了什么?请将代码添加到问题本身。评论中没有可读性。我已经做了编辑,将代码添加到问题中。例外情况是,如果用户输入的动物不在那里,会发生什么?出于某种原因,我使用此选项时删除的行是1、2、6、7和9?我还试图将动物的“名称”作为字符串输入来删除它,而不是一行数字,因为它对用户来说是未知的信息。很多其他行在使用时被删除。嘿,我编辑了代码,你能再试一次吗这次发生的事,我输入了“1”和“狼蛛”作为测试,什么也没有发生。嘿,如果文件中有
Tarantula
,则必须输入
Tarantula
,才能删除该行。代码不区分大小写。但是,我现在添加了不区分大小写。请再试一次。恐怕代码仍然无法删除“狼蛛”行。现在可以吗?