I am working on an assignment for school, and am having some trouble with one of the functions.
The assignment is a simple contact manager application and I am having trouble with the delete contact function. The instructions say to first display a numbered list of contacts from a txt file and ask the user which number they want to delete. I should then iterate through the file using a for loop and a counter. The program should add each line to the empty string when the counter does NOT equal the user input. It should then write the new list to the txt file.
The problem I am having is that when I enter a number it deletes that number and everything below it. It is like the loop stops when it matches the counter to user input. Here is the code I have so far for the delete contact function:
def del_contact(contacts):
view_contacts(contacts)
choose_contact = int(input("Please enter the number of the contact you wish to delete: "))
contacts_file = open(contacts, 'r')
new_list = ""
line_count = 1
for line in contacts_file:
if line_count != choose_contact:
new_list = line
line_count = 1
contacts_file.close()
print(new_list)
#contacts_new = open(contacts, 'w')
#contacts_new.write(new_list)
#print("Contact deleted.")
print()
I am brand new to this so I am sure it is something simple I am missing.
CodePudding user response:
When line_count == choose_contact
you don't increment line_count
by 1
:
if line_count != choose_contact:
new_list = line
line_count = 1
Next time the for
loop runs the line_count
value will still be the same and will still be equal to choose_contact
. You should increment line_count
no matter what (note the indentation):
if line_count != choose_contact:
new_list = line
line_count = 1
That being said, it is better to use enumerate
instead of keeping your own counter in such loops.