Elixir: Write to a file and create parent directories if they don't exist - in one line

Viewed 3019

Is there a function in Elixir to:

  • write contents to a given file path (or alternatively, create the file)
  • create the parent directory is if it does not exist

Currently, I have written a function like this, although it is rather inconvenient to write this for every project where I want to write to a file whose parents may not exist yet.

defp write_to_file(path, contents) do
  with :ok <- File.mkdir_p(Path.dirname(path)),
       :ok <- File.write(path, contents)
  do
    :ok
  end
end

The most ideal situation is for something like this to exist as part of the Elixir standard library, however I cannot find something like this

File.write(path, content, create_parents: true)
1 Answers

There's nothing like that in the standard library. Though why not just do this:

File.mkdir_p!(Path.dirname(path))
File.write(path, contents)

But if you want to pass on errors from mkdir, you can simplify your code a bit like this:

with :ok <- File.mkdir_p(Path.dirname(path)) do
  File.write(path, contents)
end
Related