Skip to content

Commit

Permalink
Add function to write a csv file
Browse files Browse the repository at this point in the history
  • Loading branch information
Sidhant Godiwala committed Aug 25, 2010
1 parent 1165f5e commit 8053d0b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
4 changes: 2 additions & 2 deletions project.clj
@@ -1,6 +1,6 @@
(defproject opencsv-clj "1.0.0-SNAPSHOT"
:description "clojure wrapper for opencsv"
:dependencies [[org.clojure/clojure "1.2.0-master-SNAPSHOT"]
:dependencies [[org.clojure/clojure "1.2.0"]
[net.sf.opencsv/opencsv "2.0"]]
:dev-dependencies [[swank-clojure "1.2.0"]
:dev-dependencies [[swank-clojure "1.3.0-SNAPSHOT"]
[lein-clojars "0.5.0-SNAPSHOT"]])
17 changes: 16 additions & 1 deletion src/opencsv_clj/core.clj
@@ -1,7 +1,7 @@
(ns opencsv-clj.core
#^{:author "Sidhant Godiwala"
:doc "This file defines a clojure wrapper for the opencsv library with laziness built in."}
(:import [au.com.bytecode.opencsv CSVReader])
(:import [au.com.bytecode.opencsv CSVReader CSVWriter])
(:require [clojure.java.io :as io]))

(defn- read-csv [path]
Expand All @@ -21,3 +21,18 @@
(defn parse [path]
"Converts a csv file to a lazy sequence of maps of the values where the keys are the items in the header row"
(parse-csv (read-csv path)))

(defn dump
"Dumps a sequence of maps to a file given by path, pass a header to specify the order and columns to be written"
([path csv-seq]
(let [header (keys (first csv-seq))]
(dump path csv-seq header)))
([path csv-seq header]
(with-open [writer (io/writer path)]
(let [csv-writer (CSVWriter. writer)]
(.. csv-writer (writeNext (into-array (map str header))))
(doseq [entry (map (comp into-array
(fn [csv-entry] (map (comp str #(get csv-entry %))
header)))
csv-seq)]
(.. csv-writer (writeNext entry)))))))

0 comments on commit 8053d0b

Please sign in to comment.