Closing output file from inside the loop who open it