Operations that take time to write to files are system calls and disk I / O. The fact that the file pointer is open does not cost you anything. So naively, we could say that the second method is best.
Now, as you may know, you do not directly write files to files, it uses an internal cache in memory for files that are written, and does real I / O later. I do not know the exact details of this, and in general I do not need.
What I would suggest is a midpoint solution: make a buffer for each iteration of the loop and write it once. Thus, in order to reduce a significant part of the number of system calls and (potentially) writing to disk, but not consuming too much memory using a buffer (depending on the size of your lines, I have to take this into account).
I would suggest benchmarking for a better solution, but because of the caching performed by the system, a comparative I / O disk is a real nightmare.
source share