Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete a specific line from a file

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please help me with these issues.

>Solution :

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:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading