HomeMathEmailBlogGitHub

File I/O in Clojure

2023-06-19

The easiest way to do file reading and writing in Clojure is with slurp and spit.

Let's say we have a file named test.txt with the contents "hello!"

slurp reads from a file:

(slurp "test.txt")
=> "hello!"

and spit writes to a file:

(spit "test.txt" "goodbye!")
=> nil

The contents of test.txt are now "goodbye!"

spit can also be used to append to a file by adding :append true as parameters like so:

(spit "test.txt" "cya!" :append true)
=> nil

The contents of test.txt are now "goodbye!cya!"