将大数据结构作为EDN写入clojure中的磁盘

问题描述:

在Clojure中将数据结构写入磁盘的最习惯的方式是什么,所以我可以用edn/read读回它?我尝试以下,建议在Clojure cookbook将大数据结构作为EDN写入clojure中的磁盘

(with-open [w (clojure.java.io/writer "data.clj")] 
    (binding [*out* w] 
    (pr large-data-structure))) 

然而,这只会写的第100个项目,其次是“...”。我也尝试了(prn (doall large-data-structure)),产生了相同的结果。

我已经设法通过逐行写入(doseq [i large-data-structure] (pr i))来完成,但后来我必须在序列的开头和结尾手动添加parens以获得所需的结果。

您可以控制经由*print-length*

打印的集合中的项的数量考虑使用 spit而不是手动打开作家和 pr-str而不是手动结合 *out*。从评论

(binding [*print-length* false] 
    (spit "data.clj" (pr-str large-data-structure)) 

编辑:

(with-open [w (clojure.java.io/writer "data.clj")] 
    (binding [*print-length* false 
      *out* w] 
    (pr large-data-structure))) 

注意*print-length*有一个根的nil绑定,所以你不应该需要将它绑定在上面的例子中。我会在您的原始pr呼叫时检查当前的绑定。

+1

对于大型数据结构,使用'(pr-str)'是个好主意;它会将它打印到内存中的字符串,这可能比原始结构占用更多内存。我会简单地在OP代码中添加'* print-length *'nil绑定到绑定向量。 – 2014-11-21 15:19:10

+0

我的'* print-length *'被设置为100.罪魁祸首似乎是emacs live。见http://*.com/questions/20300594/clojure-pr-str-cutting-off-lists-100-items – pholz 2014-11-21 15:22:33

+0

@DiegoBasch好点。编辑。 – Kyle 2014-11-21 15:22:37