close output file inside the for loop, instead of defering