How to check if a directory(folder) exists?

1,861 ビュー (過去 30 日間)
Leonardo Wayne
Leonardo Wayne 2016 年 3 月 25 日
編集済み: Stephen 2020 年 8 月 11 日
I am trying to create folders using mkdir, but if I have already created that folder, how do I check that before creating it. a = mkdir(directorylocation,text1) returns 1 in variable a if the directorylocation\text1 is created and if the directory exists. What is the function or condition that checks whether directorylocation\text1 exists

採用された回答

drummer
drummer 2018 年 10 月 20 日
well, I suppose you want to create if it doesn't exist, after checking... so you could do it like that:
if ~exist(yourFolder, 'dir')
mkdir(yourFolder)
end
It basically check if youFolder does not exist. If that's true, it creates youFolder.
Cheers.
  2 件のコメント
Aritra Roy Gosthipaty
Aritra Roy Gosthipaty 2020 年 3 月 6 日
This has helped a ton!!

サインインしてコメントする。

その他の回答 (2 件)

Cosmo
Cosmo 2020 年 8 月 4 日
If you're using MATLAB R2017b or later, it's better to use isfolder rather than exist like so:
if not(isfolder(yourFolder))
mkdir(yourFolder)
end
  1 件のコメント
tjueterb
tjueterb 2020 年 8 月 11 日
In case anyone else was wondering why this solution is better:
To check the existence of a file or folder, you also can use the isfolder or isfile functions. exist searches for files and folders on the search path, which can lead to unexpected results. isfolder and isfile search for files or folders only on the specified path or in the current folder, which can lead to clearer and faster results.
(copied from the exist documentation page)

サインインしてコメントする。


Stephen
Stephen 2016 年 3 月 25 日
編集済み: Stephen 2020 年 8 月 11 日
Use exist like this:
7==exist(name,'dir') % check if folder exists
or
7~=exist(name,'dir') % check if folder does NOT exist
To avoid searching the entire MATLAB Search Path use an absolute file/folder name:

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by