How to check if a directory(folder) exists?

조회 수: 1,387 (최근 30일)
Leonardo Wayne
Leonardo Wayne 2016년 3월 25일
댓글: linhtuptit 2023년 11월 15일
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
Clancy Tan
Clancy Tan 2019년 3월 18일
thank you for your answer.
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
  댓글 수: 2
tjueterb
tjueterb 2020년 8월 11일
편집: 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)
linhtuptit
linhtuptit 2023년 11월 15일
This has helped me a lot.

댓글을 달려면 로그인하십시오.


Stephen23
Stephen23 2016년 3월 25일
편집: Stephen23 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:

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by