The following code does not look correct. The variable
i
contains the complete line, but
res
contains only the last word of the line. The chances are that the two will never be the same.
if i != res:
f.write(i)
Take a look at
Built-in Types — Python 3.10.6 documentation[
^] for the functions that can be used to remove data from the end of a string.
And you should not write back into your original file, as if anything causes your program to fail mid-processing then all your data may be lost. You should read from the input file, but write the updated information to a new file. That way you can check that the new data is correct before you destroy the original.