I propose extension of the csv.ijs package to:
  * support appending arrays to an existing csv file,
  * optionally use a custom delimiter other than comma.

Existing code that uses the package should not be affected.
The new script is given below. Compare with the current csv.ijs using:
open 'csv'

Are there any objections or suggested improvements?

NB.============ proposed csv.ijs script =====================
NB. read/write comma-separated value data (*.csv) files

NB. main definitions:
NB. [delim] readcsv file  - reads data into a boxed array
NB. dat  writecsv file[;delim] - writes an array to a csv file
NB. dat appendcsv file[;delim] - appends an array to a csv file
NB. [delim] makecsv dat   - takes array and creates csv string
NB. [delim] fixcsv dat    - takes csv string and creates boxed array
NB. Default delimiter is ','

require 'files strings'

cocurrent 'z'

NB. =========================================================
extcsv=: , #&'.csv' @ (0: = '.'"_ e. (# | i:&PATHSEP_j_) }. ])

NB. =========================================================
NB.*appendcsv v appends an array to a csv file
appendcsv=: 4 : 0
'fln delim'=. 2{.!.(<',') boxopen y
dat=. delim makecsv x
dat fappends extcsv fln
)

NB. =========================================================
chopcsv=: 3 : 0
',' chopcsv y
:
dat=. y,x
b=. dat e. x
c=. ~:/\dat='"'
msk=. b>c
if. 0=+/msk do. msk=. (#msk){.1 end.
dat=. msk <;._2 dat
b=. '"'={.@(1&{.) &> dat
dat=. b }.each dat
b=. '"'={.@(_1&{.) &> dat
dat=. (-b) }.each dat
)

NB. =========================================================
NB.*fixcsv v convert csv data into J array
fixcsv=: 3 : 0
',' fixcsv y
:
b=. y e. LF
c=. ~:/\y='"'
msk=. b > c
> msk <@(x&chopcsv) ;._2 y
)

NB. =========================================================
NB.*readcsv v reads csv file into a boxed array
readcsv=: 3 : 0
',' readcsv y
:
dat=. freads extcsv y
if. dat -: _1 do. return. end.
x fixcsv dat
)

NB. =========================================================
NB.*makecsv v takes array and creates csv string
makecsv=: 3 : 0
',' makecsv y
:
dat=. ,each 8!:2 each y
f=. '"'&,@(,&('"',x))@(#~ >:@(=&'"'))
dat=. f each dat
f=. <@(,&LF)@}:@;
dat=. ;f"1 dat
)

NB. =========================================================
NB.*writecsv v writes an array to a csv file
writecsv=: 4 : 0
'fln delim'=. 2{.!.(<',') boxopen y
dat=. delim makecsv x
dat fwrites extcsv fln
)
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to