I have a vehicle database in a .txt file. Each Vehicle is in a separate line, has an ID, and can either be "active" or "inactive".
I'm writing the function "change_status()". This function will receive an input (The ID), cycle through the .txt file to find the line with said ID, and then either replace the word "active" with the word "inactive", or the word "inactive" with the word "active".
Everything in my function is working, except one thing. I don't know how to overwrite the existing line (the one I am reading), instead of just writing a new line with the status change at the bottom of the txt file, which is what I'm getting.
def change_status():
id_to_change = input("Insert the ID of the Vehicle which you want to deactivate/activate: ")
with open("Vehicles.txt", "r+") as file:
lines = file.readlines()
for line in lines:
if id_to_change in line:
if "active" in line:
new_line = line.replace("active", "inactive")
file.write(new_line)
else:
new_line = line.replace("inactive", "active")
file.write(new_line)
else:
pass
print("VEHICLE STATUS SUCCESSFULLY CHANGED")