Fixed to write file after every loop