How, in smalltalk, to read and process the contents of a CSV file

I am trying to read and process the contents of a csv file in smalltalk (visualworks), but it seems to me not easy to get a string to be split into an array. Below is the code I managed to get. I miss the part that breaks the contents of the myLine variable, which is a comma-delimited string, into an array of strings to be added to TwoDList. Please help with any information you may have about how to approach this, please. thanks

SpreadsheetReadCSV: inFilename |inStream myLine rcnt| rcnt := 0. " scan thru the text lines, using a traditional i/o loop " inStream := (inFilename asFilename) readStream . [ inStream atEnd ] whileFalse: [ rcnt := rcnt + 1. myLine := inStream upTo: Character cr. "Process the commadelimited string here" ]. inStream inspect. inStream close. ^myLine. 
+6
source share
4 answers

1) You can also turn a line into a stream, so you can use the same technique that was used to parse the file into lines:

 myLine := (inStream upTo: Character cr) readStream. [ myLine atEnd ] whileFalse: [ | myCell | myCell := myLine upTo: $,. "Do whatever with the cell" ] 

2) You can break the string into pieces using tokensBasedOn:

 myLine tokensBasedOn: $, 
+6
source

You might want to check out the CSVParser project on squeaksource. It shouldn't be hard to get it working in Visualworks.

This will give you support for all csv files (e.g. with escaped characters, quotation marks, etc.)

Also see this post.

+3
source

Someone has ported the NeoCSV parser from Pharo to VisualWorks. This may solve your problem.

+2
source

Probably the fastest way is to download the "GHCsvImportExport" package. Then you can do:

 | reader lines | reader := CsvReader onFileNamed: aFilename. [lines := OrderedCollection new. [reader atEnd] whileFalse: [lines add: reader nextLine.]] ensure: [reader close]. lines inspect. 
+1
source

Source: https://habr.com/ru/post/910507/


All Articles