openTextWriter() append w/o headers if already there

Hi,
we often need to update with one datamapper postprocessor script different text file for each record. To do so, the openTextWriter() is within the for loop, to open and close the correct text file to append the data.

Is there a more clever way than the one below to avoid writing the headers IF the file already has lines?
Any ideas are much appreciated, thanks.

for(var i=0;i<data.records.length;i++) {

	var filepath = 'C:\\Secure Folder\\Portal\\OneDrive - ΠΑΠΑΔΟΠΟΥΛΟΣ ΑΕ\\INTRUM\\OUT\\'+acsdate+'_'+acscode+'_ACSConnectImport.txt';
	
	var file = openTextWriter(filepath,"ISO-8859-7",1);
	file.close();
	
	filecheck = openTextReader(filepath,"ISO-8859-7",1);
	
if (filecheck.readLine()==null) {
    	file = openTextWriter(filepath,"ISO-8859-7",1);
    	file.write(headers);
    	file.write('\n');
} else { file = openTextWriter(filepath,"ISO-8859-7",1); }
	
	f1 = .......

str = f1+';' + ......;
	file.write(str);
	file.newLine();
	file.close();
	
	}

You should check for the file before the loop, not inside the loop. Something like the following would do what you’re looking for:

var filepath = 'C:\\Tests\\Output\\Output.txt';
var fileExists, file;
try {
	file = openTextReader(filepath,"ISO-8859-7");
	file.close();
	fileExists = true;
} catch (e) {
	fileExists = false;
} finally {
   	file = openTextWriter(filepath,"ISO-8859-7",1);
	if(!fileExists)	{
    	file.write('header1;header2;header3\n');
	} 
}

var oneLine;
for(var i=0;i<data.records.length;i++) {
	oneLine = '';
	oneLine += data.records[i].fields.Field1 + ';';
	oneLine += data.records[i].fields.Field2 + ';';
	oneLine += data.records[i].fields.Field3;
	oneLine += '\n'
	file.write(oneLine);
}
file.close();
1 Like

The problem is I don’t know the filename before the loop. Field values of each record are used to build the filename.

Ahhh…
If each record has an independent text file, then you have no choice but to check its existence in each iteration of the loop.

However, if many different records can append data to common files, then you could check for the presence of the file the first time a record attempts to access it. Once the record is finished with it, you would store the name of the file in an array.

The following iterations could then look in that array for the name of the file: if the name is in the array, then it means a previous record has already validated that the file exists, which means you can append the data to the existing file. If not, then you create the file with the headers, append the data, and record the name of the new file in the array.

yes, different records append to common files. I will try to store the name in an array.
Thank you, @Phil!