I am having difficulty deleting a specific record from a text file when using Python.
I have a customer CSV file which has four records. What I would like to do is ask the user to select a record by typing in the customer ID and then using that to find and delete the record, however, the code I have currently deletes any line with the entered number.
This is the code:
def deleteCustomer(login):
print("\n***********\n Delete a customer\n*************\n")
with open ("customers.txt") as f:
print("CustID\t Name \t\t\t Customer Town \t Customer Tel Number")
for row in f:
field = row.split(",")
custID = field[0]
custFName = field[1]
custLName = field[2]
custTown = field[3]
custTelNum = field[4]
print(custID,"\t" ,custFName,custLName,"\t\t" ,custTown,"\t" ,custTelNum)
while True:
with open ("customers.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
searchID = input("Please enter the CustID you wish to delete :")
for line in new_f:
if searchID not in line:
f.write(line)
f.truncate()
sleep(2)
viewCustomers(login)
When I run the code it will do the following:
***********
Delete a customer
*************
CustID Name Customer Town Customer Tel Number
1 Jamie John London 01792883844
2 Jim Jones Paris 01792885877
3 Bob Jones New York 01523654785
4 Alf Fisher Cardiff 01452365896
Please enter the CustID you wish to delete :
If I enter 4 then it will remove every record apart from Jim Jones as he does not have a '4' in the field.
*****************
View Customers
*****************
CustID Name Customer Town Customer Tel Number
2 Jim Jones Paris 01792885877
Returning to the main menu in 3 seconds...
Where have I gone wrong?