简体   繁体   中英

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 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM