Clojure: Printing Out Parsed .csv File

A long time ago, when I first started to learn how to program, I was taught a basic programming fundamental. In order to test your program, your program needs to be able to read and write to some device, preferably a terminal. One of my first goals in learning Clojure was to be able to read and write on a command line and process files.

In my line of work, quite a bit of which is involved with data transaction between applications, our form of currency is the comma-separated values file, known as a “dot csv” (.csv) file. Almost every proprietary spreadsheet program, like Excel and open source spreadsheet like knows how to read and write a .csv file, so this seemed like a good place to start. Almost every commercial application that uses a database, like a general ledger accounting program, knows how to create and import a .csv file.

With a lot of support from the Clojure group on Google Groups — — this is an interim program, whose file name is hardwired. Nevertheless, it prints out the first column of data quite nicely.

(ns test-csv
  (:use clojure-csv.core))</code>

(defn process-file
  "Process csv file and prints first item in every row"
  (let [data (slurp file-name)
        rows (parse-csv data)]
  (dorun (map #(println (first %)) rows))))

(defn -main [&amp; args]
  (process-file "resultset.csv"))

This is a fairly unsophisticated program. The function uses the slurp function to read in the file, and also uses the clojure-contrib library module clojure-csv to parse the csv file. In this case, I wanted the first column of the spreadsheet. clojure-csv returns a lazy sequence of rows from the spreadsheet. The first function grabs the first column.

Edit 06/21/2011:

As the Google Clojure Users Group pointed out, here is a better way to handle a default file


(defn -main [&amp; args]
 (with-command-line args
 "Get csv file name"
 [[file-name ".csv file name" "resultset.csv"]]
 (println "filename:" file-name)
 (process-file file-name))

Leave a comment

Filed under Clojure

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s