I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory
Create a new file, copy lines from the old to the new, and do the replacing before you write the lines to the new file.