Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most concise Clojure equivalent for Ruby's Dir.glob()?

Tags:

ruby

clojure

What's the easiest way to do something like this in Clojure?

require 'csv'
Dir["data/*.csv"].each do |file|
  File.readlines(file).each do |line|
    x, y, z = *CSV.parse_line(line)
    # process this data
  end
end
like image 232
dan Avatar asked Feb 16 '11 17:02

dan


2 Answers

This is the shortest I've seen:

(require '[clojure.java.io :as io])

(filter #(.endsWith (.getName %) ".csv") (file-seq (io/file dir))))

From https://github.com/brentonashworth/one/blob/master/src/lib/clj/one/reload.clj#L28

like image 155
Jeroen van Dijk Avatar answered Sep 20 '22 18:09

Jeroen van Dijk


Probably not the most concise possible, but perhaps something like the following?

(use 'clojure-csv.core)

(doseq [file (.listFiles (File. "data/"))]
  (if (.matches (.getName file) ".*[.]CSV$")
    (doseq [[x y z] (parse-csv (slurp file))]
       "... do whatever stuff you want with x, y, z..."))))

N.B. uses the clojure-csv library.

This would be more elegant and shorter if I could find an obvious way to get a filtered directory list without resorting to regexes.... but it eludes me for the moment

UPDATE:

Brian's link to Java support for globbing is also useful and interesting and offers a more general/robust approach than simple regexes - however it depends on Java 1.7 (too cutting edge for some?) and it doesn't really shorten the code much.

like image 33
mikera Avatar answered Sep 19 '22 18:09

mikera