At the point in your function where you're about to append some data into the file, test whether the file exists.
If the file does not exist, then write the column headers into the file.
Then, append the data into the file, regardless of whether you just wrote the headers or not.
In the second and subsequent calls (recursive or not), the file will exist and so the headers will not be repeated.
Regards,
Phill W.