[英]How can I delete a specific line from a txt file based on user input?
How do I go about deleting a specific line in a text file that is based on the user input?如何删除基于用户输入的文本文件中的特定行?
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)
Any help is appreciated, thank you!任何帮助表示赞赏,谢谢!
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)
Input file:输入文件:
line 1
line 2
line 3
line 4
may name is sudipto
my name is sudiptoandiloveprogramming
user input: sudipto
Output file after delete: Output文件删除后:
line 1
line 2
line 3
line 4
my name is sudiptoandiloveprogramming
Try this -尝试这个 -
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')
This should delete the line in which the input animal is there这应该删除输入动物所在的行
EDIT -编辑-
It should be A3_s3902169_stock.txt
.它应该是
A3_s3902169_stock.txt
。 You need to add that extension .txt
您需要添加该扩展名
.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.