-2
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 cant seem to find a solution for this. I want to delete lines[i] up to lines[i+3] if confirmed. This is a part of a much bigger calorie tracking program

  • The easiest would be to build a new list of lines by keeping the ones you want, rather than trying to delete the ones you don't want, then write everything back. – Thierry Lathuille Aug 20 '22 at 10:44
  • It would eventually be a long list of saved foods. Why is it so hard to just delete some lines? – SohrabFarjami Aug 20 '22 at 10:47
  • Does this answer your question? [How to search and replace text in a file?](https://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file) – user47 Aug 20 '22 at 11:04

1 Answers1

2

It may be a bad idea to delete items from an iterable while being in iteration as it may cause problems along the way. I suggest to (1) open the file in read mode, (2) save only the desired lines (or new_text), and (3) open another/same file in write mode.

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)

Or you may overwrite the existing text file if you so want:

with open("FoodList.txt", "w") as f:
    f.write(new_text)
Jobo Fernandez
  • 905
  • 4
  • 13