Your mistake is not formatting your question so that we can read it.
Your coding mistake is mixing reading and writing to the file at the same time. You read a line then write a line overwriting content in the file that followed the content you just read. This would be more obvious if you mixed up line lengths more.
Usual practice is to create an output file to write the updated content to, then after the update is complete delete the old file and rename the new version to the name of the old version.
Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond