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

  • 3
    $\begingroup$ Check with FileExistsQ and create with CreateDirectory: If[! FileExistsQ[file], CreateDirectory[file]]. $\endgroup$ Aug 3, 2018 at 8:25
  • 3
    $\begingroup$ 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. $\endgroup$
    – jkuczm
    Aug 3, 2018 at 14:18

2 Answers 2

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

Ref: FileType, CreateDirectory

Ideally, also check if CreateDirectory succeeded.

  • $\begingroup$ I forgot about FileType, it is a nice alternative to FileExistQ[""] issue. $\endgroup$
    – 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:

  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:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.