Function Repository Resource:

EnsureDirectory

Source Notebook

Ensure that a directory exists, no matter what

Contributed by: Bob Sandheinrich

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 newly created directory.
Any needed intermediate directories are created.

Examples

Basic Examples (1) 

Create a new subdirectory in your current working directory:

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

Scope (1) 

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]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 03 December 2018

License Information