ClojureDocs

Nav

Namespaces

spit

clojure.core

Available since 1.2 (source)
  • (spit f content & options)
Opposite of slurp.  Opens f with writer, writes content, then
closes f. Options passed to clojure.java.io/writer.
6 Examples
user=> (spit "flubber.txt" "test")
nil
user=> (slurp "flubber.txt")
"test"
user=> (spit "event.log" "test 1\n" :append true)
nil

user=> (spit "event.log" "test 2\n" :append true)
nil

user=> (println (slurp "event.log"))
test 1
test 2

nil
(defn append-to-file
  "Uses spit to append to a file specified with its name as a string, or
   anything else that writer can take as an argument.  s is the string to
   append."     
  [file-name s]
  (spit file-name s :append true))
;;Create a record and save a log message to a log file
;;Constructor with side effects

;;define a Person record
(defrecord Person [fname lname])

;;define a function to save a log message into the log.txt using spit and :append
(defn log-entry [msg] (spit "log.txt" (apply str msg "\n") :append true))

;;build the constructor which: 1) log the message; 2)create a Person
(defn make-person [fname lname]
  (log-entry (apply str "[log] New Person created : " lname "," fname))
    (->Person fname lname))

;;create a person
(def person (make-person "John" "Smith"))

;;print the content of the log.txt to the console
(println  (slurp "log.txt"))
; ClojureCLR doesn't use :append, use this instead
(spit "hi.txt" "Test 1\n" :file-mode System.IO.FileMode/Append)
;; Spitting map, adds "," between key-value pairs
(spit "hi.txt" {:a 1 :b 2})

;; Now let's read it
(slurp "hello.txt")
;; => "{:a 1, :b 2}"
See Also

Opens a reader on f and reads all its contents, returning a string. See clojure.java.io/reader for...

Added by jafingerhut

Attempts to coerce its argument into an open java.io.Writer. Default implementations always retur...

Added by jafingerhut

Sequentially read and evaluate the set of forms contained in the file.

Added by AtKaaZ

Given the same arg(s) as for file, creates all parent directories of the file they represent.

Added by timgilbert
2 Notes
    By , created 8.7 years ago

    The only valid options for spit are :append and :encoding.

    By , created 5.0 years ago

    Valid options include:

    :append    true to open stream in append mode
    :encoding  string name of encoding to use, e.g. \"UTF-8\".