It's not easy to replace a line of text in a file, because if the replacement line is a different size than the original, you have to change the positions of the remaining characters in the file.
Unless you want to get into databases, the easiest most reliable way to change the contents of a file is to copy the entire file into a new file with a different name. Once that step is complete, you can delete the original file and rename the new file to have the same name as the original.
Obviously this technique does not scale well to very large files, but if you are going to deal in this way with very large files, you will have other problems to solve as well.