How to spit to a new file most easily?

It’s probably java convention, but by default spit complains if the target file doesn’t exist yet. I’m sure there is a simple solution to just create the thing, but I only see the :append option listed in online options, but I don’t want to care about if the file has been written before. I want spit to behave like bash echo "something" > file.txt. What’s the simple answer?

(spit "foo.txt" "Some text!")

That will create foo.txt if it does not exist. However, the directory has to exist so this will fail:

(spit "no/such/folder/foo.txt" "Some text!")

You need to make the parent folders first. You can use make-parents - | ClojureDocs - Community-Powered Clojure Documentation and Examples for that.

Note that bash/zsh also require that the folder exists!

$ echo something > dir1/dir2/file
zsh: no such file or directory: dir1/dir2/file
$ # mkdir -p can create as many directories as you want
$ mkdir -p dir1/dir2
$ echo something > dir1/dir2/file
$ cat dir1/dir2/file

An alternative to is babashka.fs/create-dirs:

1 Like