LispCookbook / cl-cookbook

The Common Lisp Cookbook

Home Page:http://lispcookbook.github.io/cl-cookbook/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature Request: Recommend and demonstrate a library for csv parsing.

jgarte opened this issue · comments

Just making a TODO here for adding a tutorial on how to parse CSV.

I realize that you can parse csv with split-sequence but might be nice to show to do it with a proper csv parser.

This might be a good candidate/starting point:

https://github.com/AccelerationNet/cl-csv#examples

;; read a file into a list of lists
(cl-csv:read-csv #P"file.csv")
=> (("1" "2" "3") ("4" "5" "6"))

;; read a file that's tab delimited
(cl-csv:read-csv #P"file.tab" :separator #\Tab)

;; read a file and return a list of objects created from each row
(cl-csv:read-csv #P"file.csv"
                 :map-fn #'(lambda (row)
                             (make-instance 'object
                                            :foo (nth 0 row)
                                            :baz (nth 2 row))))
;; read csv from a string (streams also supported)
(cl-csv:read-csv "1,2,3
4,5,6")
=> (("1" "2" "3") ("4" "5" "6"))

;; loop over a CSV for effect
(let ((sum 0))
  (cl-csv:do-csv (row #P"file.csv")
    (incf sum (parse-integer (nth 0 row))))
  sum)
  
  
;; loop over a CSV using iterate
(iter (for (foo bar baz) in-csv #P"file.csv")
  (collect (make-instance 'object :foo foo :baz baz)))