0

I am trying to make a simple "to do list" that you can print it all or add or remove from/to the list. however it doesn't seem to remove anything from the list, but it doesn't give me any errors. I'm new to python so this code is probably very bad:

print("Welcome to the to do list!")
ch1 = input(" Do you want to remove/add/read answer with(see , add , remove )")
if ch1 == "see":
    with open("list.txt") as a:
        for line in a:
            print(line)
elif ch1 == "add":
    with open("list.txt", "a+") as f:
        wr = input("What do you want to add to the list?")
        f.write('\n'+wr)
elif ch1 == "remove":
    with open("list.txt", "r+") as f:
        for line in f:
            print(line)
        r = input("Which line do you want to remove?")
        d = f.readlines()
    with open("list.txt", "r+") as s:
        for line in s:
            if line != r:
                s.writelines(line)
else: print("Invalid mode")

I was trying to remove a line in a text file by using an if statement that checks if the line is not equal to the line I want to remove, which should prevent the line I want to remove from being written, but it doesn't seem to remove anything nor it gives me any errors

Samy
  • 1

1 Answers1

0

In the first open file, d.readlines() will read nothing because you already read all content of the file above with for line in f: (you can research about file cursor and how programming language reads a file).

In the second open file, you should read from d and write as s file handler. Because read and write at the same time will not work. You must line.strip() because when read a line from file, it contains \n (line break character). Call .strip() will remove this character. You also need to change file mode to w+. w will clear the file before it writes. You can read more in this.

    with open("list.txt", "r+") as f:
        d = f.readlines()
        for line in d:
            print(line)
        r = input("Which line do you want to remove?")
    with open("list.txt", "w+") as s:
        for line in d:
            if line.strip() != r:
                s.writelines(line)
vuongpaioz
  • 36
  • 4