Function Repository Resource:

EnsureFilePath

Source Notebook

Create the parent directories necessary to fill out a given file path

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["EnsureFilePath"][path]

creates the parent directory of path if it does not already exist and returns the full path.

Details and Options

In ResourceFunction["EnsureFilePath"][path], path can be any of the following:
"string"a file path given as a String
File[]a File
LocalObject[]a LocalObject
CloudObject[]a CloudObject
If the parent directory is a file that already exists, it will be moved into a directory of that name.

Examples

Basic Examples (3) 

Make sure the parent directory of a file exists:

In[1]:=
ResourceFunction["EnsureFilePath"]["path/to/file.txt"]
Out[1]=
In[2]:=
DirectoryQ["path/to"]
Out[2]=

Ensure a file path for a CloudObject:

In[3]:=
ResourceFunction["EnsureFilePath"][CloudObject["path/to/file.txt"]]
Out[3]=
In[4]:=
DirectoryQ[CloudObject["path/to"]]
Out[4]=

Ensure a file path for a LocalObject:

In[5]:=
ResourceFunction["EnsureFilePath"][LocalObject["path/to/file"]]
Out[5]=
In[6]:=
DirectoryQ["/Users/richardh/Library/Wolfram/Objects/path/to"]
Out[6]=

Scope (4) 

EnsureFilePath can also handle File expressions:

In[7]:=
ResourceFunction["EnsureFilePath"][File["file/example/data.txt"]]
Out[7]=

EnsureFilePath does not create the target file, only the parent directory:

In[8]:=
ResourceFunction["EnsureFilePath"]["path/to/new/file.txt"]
Out[8]=
In[9]:=
FileExistsQ[%]
Out[9]=
In[10]:=
DirectoryQ[DirectoryName[%%]]
Out[10]=

If the parent directory is a file that already exists, it will be moved into a directory of that name:

In[11]:=
Put[1, "data"];
ResourceFunction["EnsureFilePath"]["data/file"]
Out[12]=
In[13]:=
DirectoryQ["data"]
Out[13]=
In[14]:=
Get["data/data"]
Out[14]=

The same is true for a CloudObject:

In[15]:=
CloudPut[1, "data"];
ResourceFunction["EnsureFilePath"][CloudObject["data/file"]]
Out[16]=
In[17]:=
DirectoryQ[CloudObject["data"]]
Out[17]=
In[18]:=
CloudGet["data/data"]
Out[18]=

Applications (1) 

Make sure a target directory exists when writing to a file:

In[19]:=
Put[10!, "this/path/does/not/exist/data.wl"]
Out[19]=
In[20]:=
Put[10!, ResourceFunction["EnsureFilePath"][
  "this/path/does/not/exist/data.wl"]]
In[21]:=
Get["this/path/does/not/exist/data.wl"]
Out[21]=

Possible Issues (1) 

The file will only be moved into the target directory if it differs by one level:

In[22]:=
Put[1, "data/file"];
ResourceFunction["EnsureFilePath"]["data/file/path/too/deep"]
Out[23]=
In[24]:=
ResourceFunction["EnsureFilePath"]["data/file/ok"]
Out[24]=

Version History

  • 2.0.0 – 07 June 2019
  • 1.0.0 – 14 November 2018

Related Resources

License Information