Just work on your "lines" and write them out as soon as you are finished with them.
file = open('myFile.exe', 'r+b')outfile = open('myOutfile.exe', 'wb')for line in f: #Here you are going to mutate the CURRENT line. outfile.write(line)file.close()outfile.close()