with-open

added
1.0

ns
clojure.core

type
macro

(with-open bindings & body)

bindings => [name init ...]

Evaluates body in a try expression with names bound to the values
of the inits, and a finally clause that calls (.close name) on each
name in reverse order.

                ;; Opens the file 'myfile.txt' and prints out the contents.  The 
;; 'with-open' ensures that the reader is closed at the end of the 
;; form.  
;; 
;; Please note that reading a file a character at a time is not 
;; very efficient.

user=> (with-open [r (clojure.java.io/input-stream "myfile.txt")] 
         (loop [c (.read r)] 
           (if (not= c -1)
             (do 
               (print (char c)) 
               (recur (.read r))))))

            
                (defn write-csv-file
  "Writes a csv file using a key and an s-o-s (sequence of sequences)"
  [out-sos out-file]

  (spit out-file "" :append false)
  (with-open [out-data (io/writer out-file)]
      (csv/write-csv out-data out-sos)))