How to check if a directory(folder) exists?

1.740 Ansichten (letzte 30 Tage)
Leonardo Wayne
Leonardo Wayne am 25 Mär. 2016
Kommentiert: linhtuptit am 15 Nov. 2023
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

Akzeptierte Antwort

drummer
drummer am 20 Okt. 2018
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 Kommentare
Clancy Tan
Clancy Tan am 18 Mär. 2019
thank you for your answer.
Aritra Roy Gosthipaty
Aritra Roy Gosthipaty am 6 Mär. 2020
This has helped a ton!!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Cosmo
Cosmo am 4 Aug. 2020
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 Kommentare
tjueterb
tjueterb am 11 Aug. 2020
Bearbeitet: tjueterb am 11 Aug. 2020
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 am 15 Nov. 2023
This has helped me a lot.

Melden Sie sich an, um zu kommentieren.


Stephen23
Stephen23 am 25 Mär. 2016
Bearbeitet: Stephen23 am 11 Aug. 2020
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:

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by