如果在 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)
基本上我需要这个来找到用户输入和包含那个词的那一行来删除整行。我不知道该怎么办,被困住了。我可以帮忙吗
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)