0

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")
  • 1
    There is no concept of "replace a line" on file system level. As long as the file size changes, you'll probably need to write the complete file from scratch. If it's GBs of data, you'll need a well through file format so you can change a line without the need of moving other data – Thomas Weller Jan 24 '19 at 16:11
  • I think the previous comment, and the answer provided are spot on. Here's another question that might be helpful: https://stackoverflow.com/questions/10507230/insert-line-at-middle-of-file-with-python – Kurt Schwanda Jan 24 '19 at 16:15

1 Answers1

1

The easiest -- though obviously not most efficient -- solution is to rewrite the entire file. Open a different file for output, and instead of passing in the else block, write the unmodified line if no match occurred. Editing the file in place is not an operation supported directly by the filesystem, as Thomas Weller pointed out, so you would need some more logic to do anything else.

Jack Meagher
  • 306
  • 1
  • 6