why a loop will cause this problem.
As the code repeats the loop, more memory is required.
What action I takes to identify is the size or loop problem
If it runs for a few records (make a tiny test input file and try it) and fails with full volume, it is probably because of the incrementally required memory because of processing the file. If it will not run at all due to memory, it is probably too large. One other consideraton is that if the code has a problem and goes into a loop that requires more and more menory, this could also cause the problem. You should be able to isolate which is happening with a few tests. If it appears to be in a loop, you may want to include some diagnostic code to help you debug.
If it is size problem then may be directly write to the file will do
Possibly, but if the problem is due to volume, you should probably look for a way to run your code in batch and possibly use a language better suited for file processing.