Wolfram Computation Meets Knowledge

EnsureDirectory

Contributed by: Bob Sandheinrich

Ensure that a directory exists, no matter what

ResourceFunction["EnsureDirectory"][dir]

creates a directory dir regardless of existing files and directories.

Details and Options

The directory path is returned.
If a directory already exists, nothing happens.
If a file exists at the desired location it is moved into the new directory.
Any needed intermediate directories are created.

Examples

Basic Examples

Create a new subdirectory in your current working directory:

In[1]:=
ResourceFunction["EnsureDirectory"][
 FileNameJoin[{"MyDir", "dir1", "dir2"}]]
Out[1]=

Scope

If a file is in the way, it is moved into the new directory:

In[2]:=
Put["Hello World", "BobSaysHello"]
In[3]:=
ResourceFunction["EnsureDirectory"]["BobSaysHello"]
Out[3]=
In[4]:=
FileSystemMap[Get, "BobSaysHello"]
Out[4]=

Resource History