· Mar 3, 2023

How do I add headers to a CSV using ObjectScript?

I'm wondering how I would go about adding headers to a csv file which has already been created. I am unfamiliar with ObjectScript. 

For example if I were to use R, I would simply write..

test <- read.csv("file/path/example/Extract.csv", header=FALSE)
colnames(test) <- c("A","B","C","D","E")

I do not have embedded Python installed either as I would know how to do it in that also.

How could I mirror this in ObjectScript please?

My current create file method:

Discussion (3)2
Log in or sign up to continue

Some ideas for an Operation.

Expose the Comma delimited headings to be configurable via new property and settings.

Toggle the overwrite/append mode, if set to overwrite, to ensure the heading is added to new files

So code code might be something like:

/// The type of adapter used to communicate with external systems
Parameter ADAPTER = "EnsLib.File.OutboundAdapter";
Property Adapter As EnsLib.File.OutboundAdapter;
Property CSVHeaderRecord As %String;
Parameter SETTINGS = "CSVHeaderRecord:Basic"; 
Method TestWrite(pRequest As Ens.StringContainer, pResponse As Ens.StringContainer) As %Status
 set filename="OutputTest.csv"
 set originalOverwrite=..Adapter.Overwrite
 if ""'=..CSVHeaderRecord {
   if originalOverwrite {
     set tSC=..Adapter.PutLine(filename,..CSVHeaderRecord)
     set ..Adapter.Overwrite=0
else {
     if '##class(%File).Exists(..Adapter.fixPath(..Adapter.FilePath)_pFilename) {
       set tSC=..Adapter.PutLine(filename,..CSVHeaderRecord)
       set ..Adapter.Overwrite=0
 set tSC=..Adapter.PutLine(filepath_filename,pRequest.StringValue)
 set ..Adapter.Overwrite=originalOverwrite
 Quit $$$OK

For updating existing files using streams:

May need to consider stream line terminators and character encoding.

ClassMethod AddCSVHeader(filepath = "", headerText = "")
set tmpStream=##class(%Stream.TmpCharacter).%New()
set updateStream=##class(%Stream.FileCharacter).%New() 
set tSC=updateStream.LinkToFile(filepath)
set tSC=tmpStream.CopyFrom(updateStream)
do updateStream.Rewind()
do tmpStream.Rewind()
do updateStream.WriteLine(headerText)
do updateStream.CopyFrom(tmpStream)
do updateStream.Flush()
do updateStream.%Save()