Commits

Miki Tebeka  committed d647eb4

Initial commit

  • Participants

Comments (0)

Files changed (4)

+syntax glob
+
+lib
+classes
+log*
+README.html
+================================
+csvlib - CSV library for Clojure
+================================
+
+About
+=====
+Library to read and write CSV files with Clojure.
+
+Usage
+=====
+::
+
+    (use 'csvlib)
+    ; Without headers
+    (let [records (csv-read "log.csv")]
+      (println ((first records) 0)))
+
+    ; With headers
+    (let [records (csv-read "log.csv" true)]
+      (println ((first records) "IP")))
+
+License
+=======
+Copyright (C) 2010 Miki Tebeka <miki.tebeka@gmail.com>
+
+Distributed under the Eclipse Public License, the same as Clojure.
+(defproject csvlib "0.1.0.0"
+  :description "A CSV library for Clojure, using csvreader.com"
+  :url "https://bitbucket.org/tebeka/csvlib/src"
+  :dependencies [[org.clojure/clojure "1.2.0"]
+                 [com.csvreader/javacsv "2.0"]])

File src/csvlib.clj

+(ns csvlib
+  (import com.csvreader.CsvReader))
+
+(defn- record-seq [filename]
+  (let [csv (CsvReader. filename)
+        read-record (fn [] 
+                      (when (.readRecord csv) 
+                        (into [] (.getValues csv))))]
+    (take-while (complement nil?) (repeatedly read-record))))
+
+(defn read-csv
+  "Return a lazy sequence of records (maps) from CSV file.
+
+  With header map will be header->value, otherwise it'll be position->value."
+  ([filename] (csv-seq filename false))
+  ([filename headers?]
+   (let [records (record-seq filename)
+         headers (if headers? (first records) (range (count (first records))))]
+    (map #(zipmap headers %) (if headers? (rest records) records)))))
+