Python Forum
delete line from a text file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: delete line from a text file (/thread-9093.html)



delete line from a text file - thesisonews - Mar-20-2018

i been trying for hours, no luck

the function ask the user what name he want to delete from the text file

def Delete_con():
    with open('phonebook1.txt', 'r+') as f:
        t = f.read()
        to_delete = input('What should we delete? : ').strip()
        f.seek(0)
        for line in t.split('\n'):
            if line != to_delete:
                f.write(line)
        f.truncate()
        return Menu()



RE: delete line from a text file - Gribouillis - Mar-20-2018

Perhaps replace line 8 with print(line, file=f)


RE: delete line from a text file - nilamo - Mar-20-2018

What errors do you get?