I'm trying to delete specific list from a text file and overwrite the original text file without using os.replace. However,i tried using truncate but nothing happen to my txt file..
Input:
def delete_tenants():
a = []
tnf = False
# while not found:
with open("tenant_application.txt", "r") as file:
lines = file.readlines()
with open("tenant_application.txt", "r") as file:
for line in file:
a = line.split(",") # split lines using comma
print(a) # display all the data in txt file
with open("tenant_application.txt", "r") as file:
delete = input("Enter the primary key to delete: ")
for line in file:
a = line.split(",") # split lines using comma
b = a[10].strip()
c = delete.strip()
d = c == b
if d:
print("Line that you want to delete:", line)
tnf = True
break
if tnf == False:
print("\nInvalid Input\n")
return delete_tenants()
if tnf == True:
input1 = "tenant_application.txt"
#
with open(input1, "r+") as file1:
lines = file1.readlines()
file1.seek(0)
for i in lines:
if i not in a:
file1.write(i)
file1.truncate()
My text file:
Celine ,43,Female,Selangor,Kuala Lumpur,Happy Garden,Persiaran Sungai Long 2 ,2003-04-03 00:00:00,43000,111,0001
Jackson ,43,Female,Selangor,Kuala Lumpur,Happy Garden,Persiaran Sungai Long 2 ,2003-04-03 00:00:00,43000,111,0002
Wong ,43,Female,Selangor,Kuala Lumpur,Happy Garden,Persiaran Sungai Long 2 ,2003-04-03 00:00:00,43000,111,0003
Liew ,43,Female,Selangor,Kuala Lumpur,Happy Garden,Persiaran Sungai Long 2 ,2003-04-03 00:00:00,43000,111,0004