Question
· Jun 2, 2022

Reading a CSV file into a Variable

Hello!  I need help reading a file and putting the contents into variables.

File path would be, c:\temp\zipcitystate.csv or txt

Data looks like this

00501,Holtsville,NY
00544,Holtsville,NY
00601,Adjuntas,PR
00602,Aguada,PR

I need to add the first area to variable ZIP, Second to CITY and third to STATE. they are separated by a comma.

 

Any help would be appreciated 

Product version: Caché 2017.1
$ZV: 2017.1.0.792.0
Discussion (8)0
Log in or sign up to continue

A simple method like


ClassMethod ProcData(file = "c:\temp\zipcitystate.csv")
{
    set str=##class(%Stream.FileCharacter).%New()
    do str.LinkToFile(file)
    while 'str.AtEnd {
        set $listbuild(ZIP,CITY,STATE)=$listfromstring(str.ReadLine())
        
        // now you have the individual columns
        // in ZIP, CITY and STATE variables for further processing
        write "Zip=",ZIP,?12,"City=",CITY,?40,"State=",STATE,!
    }
    
    // depending on the way of your implementation, a "kill str"
    // would be needed to free up the file
    kill str
}

to do the job. Then call the method as

do ##class(your.class).ProcData()
// or
do ##class(your.class).ProcData("path-to-the-file")

As an ObjectScript routine, remove the "ClassMethod" keyword (which, as the name indicates, belongs to classes. Then either  add a "Public" keyword or you remove the brackets ("{", "}") too, but then all variables will have the same scope:

ProcData(file = "c:\temp\zipcitystate.csv") Public
{
    set str=##class(%Stream.FileCharacter).%New()
    do str.LinkToFile(file)
    while 'str.AtEnd {
        set $listbuild(ZIP,CITY,STATE)=$listfromstring(str.ReadLine())
        
        // now you have the individual columns
        // in ZIP, CITY and STATE variables for further processing
        write "Zip=",ZIP,?12,"City=",CITY,?40,"State=",STATE,!
    }
    
    // depending on the way of your implementation, a "kill str"
    // would be needed to free up the file
    kill str
}

Oh, and to invoke the above procedure just do a:

do ProcData^YourRoutineName()
// or
do ProcData^YourRoutineName("path-to-file")