将clojure地图/数组写入文件并将其读回 [英] Writing clojure maps/arrays to a file and reading them back

查看:185
本文介绍了将clojure地图/数组写入文件并将其读回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将clojure地图保存到一个文件,稍后再读回来处理它们。



这是我能想出的。是否有更好的方法来完成同样的事情?

  user => (def my-data(for [a [Person1Person2] b [Address1Address2] c(range 10)] {:name a:address b:index c}))
# 'user / my-data
user => (count my-data)
40

user => (defn write-data [xs](with-open [wrtr(clojure.java.io/writermy-data.txt)]
(doall n))xs))))
#'user / write-data

user => (write-data my-data)

user => (don(map#(load-string%)(line-seq rdr)(def-read-data [](with-open [rdr(clojure.java.io/readermy-data.txt)] )))))
#'user / read-data

user => (count(read-data))
40


解决方案

p>从文件中读取单个表单最简单,所以我通常把我的数据放到一个向量中。
我也喜欢使用pr或 pr-str ,而不是打印,因为它保证产生可读的数据,

 (def my-data [{:afoo:b [1 2 3]}asdf42#{1 2 3}])
spit/tmp/data.edn(with-out-str(pr my-data)))
nil
(read-string(slurp/tmp/data.edn))
[{:afoo,:b [1 2 3]}asdf42#{1 2 3}]

vs:

 (spit/tmp/data.edn(with-out-str (print my-data)))
(read-string(slurp/tmp/data.edn))
[{:a foo,:b [1 2 3]} asdf 42# 1 2 3}]

注意字符串asdf是作为符号读回的。 / p>

.toString 也可正常工作:

 (spit/tmp/data.edn(.toString my-data))
(read-string(slurp/tmp/data.edn))
[ {:afoo,:b [1 2 3]}asdf42#{1 2 3}]


I need to save clojure maps to a file and read them back later to process them.

This is what I could come up with. Is there a better way to accomplish the same thing?

user=> (def my-data (for [ a [ "Person1" "Person2" ]  b [ "Address1" "Address2"]  c   (range 10) ] {:name a :address b :index c} ))
#'user/my-data
user=> (count my-data)
40

user=> (defn write-data[xs] (with-open [wrtr (clojure.java.io/writer "my-data.txt") ]
              (doall (map #(.write wrtr (str % "\n")) xs))))
#'user/write-data

user=> (write-data my-data)

user=> (defn read-data[] (with-open [rdr (clojure.java.io/reader "my-data.txt") ]
            (doall (map #(load-string %) (line-seq rdr)))))
#'user/read-data

user=> (count (read-data))
40

解决方案

It is easiest to read a single form to and from the file, so I usually put my data into a vector. I also prefer to use pr or pr-str rather than print because it is guaranteed to produce readable data,

(def my-data [{:a "foo" :b [1 2 3]} "asdf" 42 #{1 2 3}]) 
(spit "/tmp/data.edn" (with-out-str (pr my-data)))
nil
(read-string (slurp "/tmp/data.edn"))
[{:a "foo", :b [1 2 3]} "asdf" 42 #{1 2 3}] 

vs:

(spit "/tmp/data.edn" (with-out-str (print my-data)))
(read-string (slurp "/tmp/data.edn"))
[{:a foo, :b [1 2 3]} asdf 42 #{1 2 3}] 

notice how the string `"asdf" was read back as a symbol.

.toString also works fine:

(spit "/tmp/data.edn" (.toString my-data)) 
(read-string (slurp "/tmp/data.edn"))
[{:a "foo", :b [1 2 3]} "asdf" 42 #{1 2 3}] 

这篇关于将clojure地图/数组写入文件并将其读回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆