Is there a function in Elixir to:
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)
Create a Directory if it Does Not Exist You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose. The mkdir() method creates a single directory if it does not already exist.
A parent directory is a directory that is above another directory in the directory tree. To create parent directories, use the -p option. When the -p option is used, the command creates the directory only if it doesn't exist.
touch is not able to create directories, you need mkdir for that. However, mkdir has the useful -p / --parents option which creates a full directory structure. If you think you will need this more often and don't want to type the path twice every time, you can also make a Bash function or a script for it.
mkdir creates a file instead of directory.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With