I have a problem with my code. I am trying to delete a specific line from a file. I am making a To-Do List program in Tkinter, and I am using a Label as the to-do list. I have two buttons, 'Add Item' and 'Delete Item'. I also have an entry box, and the buttons take the string from the entry using the .get() method. The delete button is not working because I cannot find a way to delete a line from a file that the program is using to store the list. I have looked over many other posts about the same problem, but mine is different. Whenever I run the program, and I click delete item after I fill out the text box, it deletes ALL items from the file, but I only want it to delete one item. The problem is NOT the one that @JetMashKangaroo had in this post: How to delete a line from a file in Python.
Here is the snippet of code:
def dele():
global ItemName
global Display
global List
ToDoDel = ItemName.get()
new_f = List.readlines()
List.seek(0)
for line in new_f:
if ToDoDel not in line:
List.write(line)
List.truncate()
Display['text'] = List.readlines()
ItemName is the entry box. Display is the label that displays the To-Do list. List is the variable below:
List = open('***/***/To-Do_List.txt','r+')
The program works perfectly, but I cannot add this delete function because it deletes all the text from the file. the function dele is called when the button 'Delete Item' is pressed. Help would be greatly appreciated.
The most likely reason you're running into a problem is that you are attempting to modify the list while also iterating over it. Here's an example post of someone else who ran into a similar issue.
My suggestion is that you keep track of which indexes to modify within your loop, then remove them after the loop has completed.