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
Once you copy them to a variable - then what? Global variable? Depending on what you want to do with the info, I'd create a RecordMap to read the file....need more information to really say.
Yea, I'll be updating a global with the data which I know how to do, just struggling to get the info from the file.
Then I suggest creating a recordMap for the file layout, then use the EnsLib.RecordMap.Service.BatchFileService (or similar) class to read the file.
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")
Use LOAD DATA sql command.
Older approach
Does this matter if the routine is a object script routine? I have tried a lot of stuff and I keep getting various errors.
Julius I tired your code but it's failing on the first line.
Any help would be appreciated
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")
That worked! Thank you very much!