How to check whether the folder is created, and if not, create it?

Consider a .nb file. How to check whether the folder is present in notebook directory, and if not, create it?

• Check with FileExistsQ and create with CreateDirectory: If[! FileExistsQ[file], CreateDirectory[file]]. Aug 3, 2018 at 8:25
• Just use CreateDirectory. If directory already exists you'll get CreateDirectory::filex message. If non-directory file exists, with given name, you'll get CreateDirectory::dirf message. You can use Quiet and/or Check to ignore/react to those situations. Aug 3, 2018 at 14:18

With[{dirname = FileNameJoin[{NotebookDirectory[], "mydir"}]},
Switch[FileType[dirname],
None, CreateDirectory[dirname] (* create dir *),
Directory, Null (* do nothing *),
File, Print["File with same name already exists!!"] (* error! *)
]
]


Ideally, also check if CreateDirectory succeeded.

• I forgot about FileType, it is a nice alternative to FileExistQ[""] issue.
– Kuba
Aug 3, 2018 at 9:17

As noted by jkuczm in a comment, we can attempt to create the directory unconditionally but tolerate the case that the directory already exists:

Quiet[
CreateDirectory[{FileNameJoin[NotebookDirectory[], "mydir"}]]
, CreateDirectory::filex
]


This approach differs from the test-then-create approach in that it precludes the possibility of another process sneaking a file operation between the testing and creation. Of course, this possibility is not relevant for typical single-user operation.

If rather than leaving the directory empty we wish to immediately create a contained file, we can create both the directory (as needed) and the file in a single step:

CreateFile[
FileNameJoin[{NotebookDirectory[], "mydir", "myfile"}]
, CreateIntermediateDirectories -> True
]