Search code examples
pythonfileexceptiontry-except

How do I undo what I'm currently writing before close()?


for i in range(0,5):
    
    f = open("StudentRecords.txt", "a")
    try:
        f.write(input("Name: ")+"\n")
        f.write(str(int(input("ID: ")))+"\n")
        f.write(str(float(input("GPA: ")))+"\n")
    except ValueError:
        print("Error: You entered a String for ID or GPA.")
    
    f.close()

Here for example if I tried to write a string for GPA, I will catch the error and the program will move on, but the Name and ID of the same iteration will still be written I want it to only write if all the 3 data are valid.


Solution

  • As the comments said, the best approach is to validate all the data before writing anything. But if you really need to undo, you can do it by saving the file position before each record, seeking back to it, and truncating to remove everything written after.

    And rather than reopening the file for each record, you should open it once before the loop. Use with to close it automatically when the block is finished.

    with open("StudentRecords.txt", "w") as f:
        for i in range(0,5):
            try:
                filepos = f.tell()
                f.write(input("Name: ")+"\n")
                f.write(str(int(input("ID: ")))+"\n")
                f.write(str(float(input("GPA: ")))+"\n")
            except ValueError:
                print("Error: You entered a String for ID or GPA.")
                f.seek(filepos)
                f.truncate()