[英]Delete certain line from text file python
def deleteFood():
print('Enter food name')
food = input().lower()
with open("FoodList.txt") as f:
lines = f.readlines()
for i in range(len(lines)-1):
if food in lines[i]:
print('Deleting ' + lines[i] + lines[i+1] + lines [i+2] + lines [i+3] + 'Confirm? Y/N')
confirmation = input().upper()
if confirmation == 'Y' or confirmation == 'N':
if confirmation == 'Y':
我似乎無法為此找到解決方案。 如果確認,我想刪除行[i] 到行[i+3]。 這是更大的卡路里跟蹤計划的一部分
在迭代過程中從可迭代對象中刪除項目可能是個壞主意,因為這可能會導致問題。 我建議(1)以讀取模式打開文件,(2)僅保存所需的行(或new_text ),以及(3)以寫入模式打開另一個/相同的文件。
def deleteFood():
print('Enter food name')
food = input().lower()
new_text = ""
with open("FoodList.txt", "r") as f:
lines = f.readlines()
i = 0
while i < len(lines):
if food in lines[i]:
print('Deleting ' + lines[i] + lines[i + 1] + lines[i + 2] + lines[i + 3] + 'Confirm? Y/N')
while True:
confirmation = input("Confirm? ").upper()
if confirmation in ["YES", "Y"]:
i += 4
break
elif confirmation in ["NO", "N"]:
new_text += lines[i]
i += 1
break
else:
print("Invalud input.")
else:
new_text += lines[i]
i += 1
with open("FoodList_duplicate.txt", "w") as f:
f.write(new_text)
或者,如果您願意,可以覆蓋現有的文本文件:
with open("FoodList.txt", "w") as f:
f.write(new_text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.