10
$\begingroup$

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

$\endgroup$
2
  • 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

17
$\begingroup$
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! *)
 ]
]

Ref: FileType, CreateDirectory

Ideally, also check if CreateDirectory succeeded.

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

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
]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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