Search code examples
clojurewritefileline-by-line

How can I write an EDN line by line? (spit, seq of hashmaps)


I have data like that

tab = ({"123" data} {"456" data} ... 

(whatever, it is a lazy sequence of hashmaps).

I want to write it into an edn file line by line, so I did this

(map (fn[x] (spit "test.edn" x :append true)) tab)

The problem is that I would like to have this in the file :

{"123" data}
{"456" data}

But it seems to append like that

{"123" data}{"456" data}

Is there a way to solve this ? I guess I have to add "newline" but I don't know how to do it since inputs are not strings.

Thanks !


Solution

  • (doseq [x tab]
      (spit "test.edn" (prn-str x) :append true))
    

    So, for each item in tab, convert it to a readable string followed by a newline, then append that string to test.edn.

    You should not use map for this for a couple of reasons:

    1. map is lazy and therefore will not print the entire sequence unless you force it
    2. map retains the head of the sequence, which would simply waste memory here