简体   繁体   中英

How to delete a line from a separate file using python

def editTodo():
    with open ("todolist", "r") as f:
        lines = f.readlines()
        for line in lines:
            data = line.strip()
            print(f'{data}\n')
            deletion = input("What do you want to delete?")
            if deletion in data:
                with open("todolist") as f:
                    lines = f.read().splitlines()
                    lines.remove()
                print ("Successfully deleted")

This is my function for a to do list to edit their to do list. I want the user to be able to delete one of the items from their todo list but I am getting this error. TypeError: remove() takes exactly one argument (0 given) I am pretty sure there are other errors too, sorry about that.

you should get rid of the second fileopen. Iterate through lines, ask if user wants to delete. After the loop, write remaining stuff in lines to the same filename.

def editTodo():
    with open ("todolist", "r") as f:
        lines = f.readlines()
    index = 0
    while index < len(lines):
        current_event = lines[index].strip()
        print(current_event)
        deletion = input('what do you want to delete? use white space to seperate events').split(' ')
        # convert current_event to a list of things, 
        # then filter against stuff user wants to delete
        current_event = current_event.split(' ')
        current_event = list(filter(lambda item: item not in deletion, current_event))
        lindex[index] = ' '.join(current_event)
        index += 1 
    # now that we've filtered out events we deleted, write the file again
    with open('name.txt', 'w') as fileout:
        [fileout.write(item+'\n') for item in lines]

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