-2

I what to make a to do list in Python, but i am having trouble with the delete commands.

This is the code:

def add():
    adding = input("What do you want to add?: \n")
    with open("to_do_list.txt", "a") as f:
        f.write(adding + "\n")

def delete():
    deleting = input("What do you want to delete?: \n")
    with open("to_do_list.txt", "r+") as f:
        lines = f.readlines()
        for line in lines:
            if line.find(deleting) == -1:
                f.write(line)

def view():
    with open("to_do_list.txt", "r") as f:
        for line in f.readlines():
            print(line)

def close():
    exit()

while True:
    mode = input("Add to list, delete from list, view list or leave program (add/del/view/esc) \n")
    if mode == "add":
        add()
    elif mode == "del":
        delete()
    elif mode == "view":
        view()
    elif mode == "esc":
        close()
    else:
        print("Mode invalid!")
        continue

The delete command, nothing happens, I input what I want to delete but it does not delete it from the file. What do I have to change in the code so that it deletes the line that I want?

Please help me with these issues.

FlaviusKid
  • 17
  • 3
  • 1
    `for line in f.readline():` must be `for line in f.readlines():` (mind the "s" at the end!). Or, even better, `for line in f:`. – DYZ Jan 22 '22 at 22:24
  • 1
    Welcome to posting on Stack Overflow! Please take the [tour] and read [ask], especially for advice on writing a good title. For debugging help in the future, please make a [mre] including minimal code and expected output. – wjandrea Jan 22 '22 at 22:35

1 Answers1

1

This line in the view() function is your problem:

for line in f.readline():

readline() reads in a single line. Since the for-loop is iterating over a string rather than a list of strings, it iterates over each character in the line, printing one character out at a time.

You're looking for this:

# Note that it's .readlines(), not .readline()!
for line in f.readlines(): 

Or, even better:

for line in f:
wjandrea
  • 28,235
  • 9
  • 60
  • 81
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • 1
    Note that there are a lot of other `readline()` calls -- I think these should *all* be `readlines()`. – Samwise Jan 22 '22 at 22:26