in reply to Help in read and write to file at a same time in same file.

With text files you can only get this to work if the new lines are exactly the same length as the old ones. Text files are just strings of text interspaced with new-lines (on UNIX). Say you see a file in an editor that looks like this:
This is a line This is another line and so is this
In reality it looks like this (try od -xc if you are in UNIX):
This is a line\nThis is another line\nand so is this\n
Adding a # to the second line, and then rewriting it, would give us this (look carefully):
This is a line\n#This is another line\nnd so is this\n
Adding an extra character makes the line longer, so it overwrites the first character of the next line!

Write the output lines to a different file instead then, assuming it worked, rename the new file to the same name as the old one.