Home > other >  data.csv - appending to new line in CSV (clojure)
data.csv - appending to new line in CSV (clojure)

Time:06-11

I have been testing out this csv package data.csv.

I have managed to make the writing to CSV work. I am still very new to clojure/lisp.

What I cannot figure out (through testing or via the documentation), is how to add the data too a new line in the csv.

The API documentation says this:

write-csv
function
Usage: (write-csv writer data & options)
Writes data to writer in CSV-format.

Valid options are
  :separator (Default \,)
  :quote (Default \")
  :quote? (A predicate function which determines if a string should be quoted. Defaults to quoting only when necessary.)
  :newline (:lf (default) or :cr lf)

But i cannot workout how to use it this.

I am trying to add a new line for the following code:

(defn writeCSV [name]
  (with-open [writer (io/writer filePath)]
    (csv/write-csv writer
                 [[name 2]])))

Where the name is added to the next available line.

CodePudding user response:

Use the :append option of io/writer:

(require
  '[clojure.data.csv :as csv] 
  '[clojure.java.io :as io])

(with-open [writer (io/writer "/tmp/foo.csv" :append true)] 
  (csv/write-csv writer [["name" 1]]))
(with-open [writer (io/writer "/tmp/foo.csv" :append true)] 
  (csv/write-csv writer [["name" 2]]))

(println (slurp "/tmp/foo.csv"))
;;=>
name,1
name,2
  • Related