Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file-io

elixir

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)
like image 704
Dylanthepiguy Avatar asked Dec 20 '18 22:12

Dylanthepiguy


People also ask

How do you create a file in a directory if not exists?

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.

How do I create a parental path to a folder?

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.

Can touch create directories?

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.

Does mkdir create file?

mkdir creates a file instead of directory.


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
like image 77
Sheharyar Avatar answered Dec 03 '22 04:12

Sheharyar