Check if file directory exists, else create it
24 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Daniel van Huyssteen
am 8 Okt. 2024
Beantwortet: Bruno Luong
am 8 Okt. 2024
I have a code that loops through hundreds of parameter permutations. During each loop data and figures are outputted and stored. The outputs are stored in folder system with many name variations and subfolders that depend on the particular loop being run. Additionally, the number of stored outputs is not consistent.
During each loop I need to check that the specific directory exists. If it exists I need to clear the existing data. If it does not exist I need to create the directory.
I am able to check if the directory exists and clear its contents with no problems. However, I am not sure how to correctly create the directory if it does not exist. I want to use the 'mkdir' command with a concatenated string that defines the directory. If the file directory to create is called 'FullDirectory' at the moment 'mkdir' just makes a folder called 'FullDirectory' in the current directory. How do I correct this?
See the sample code below
Note: It is possible that some portion of the full directory already exists. For example, 'SubFolder' and 'SubSubFolder' could exist and only 'SubSubSubFolder' needs to be created. Alternatively, it is possible that none of the folders are pre-existing.
% Create example 'building blocks' for directory
BaseDirectory = cd;
SubDirectory = 'SubFolder';
SubSubDirectory = 'SubSubFolder';
SubSubSubDirectory = 'SubSubSubFolder';
% Assemble full directory
FullDirectory = strcat(BaseDirectory,'/',SubDirectory,'/',SubSubDirectory,'/',SubSubSubDirectory);
% Check if directory exists
if isfolder(FullDirectory) == true
% Erase contents of directory
FileTypesToErase = {'.fig','.png','.jpg','.mat'};
EraseFileContents(FullDirectory, FileTypesToErase);
else
% Create directory
mkdir FullDirectory % This part needs modification
end
function EraseFileContents(FullDirectory, FileTypesToErase)
%ERASEFILECONTENTS Erases files of specified types in directory
for i = 1:length(FileTypesToErase)
ThisFileType = FileTypesToErase{i};
ThisFileTypePattern = strcat('*',ThisFileType);
FullFilePattern = fullfile(FullDirectory, ThisFileTypePattern);
TheFiles = dir(FullFilePattern);
for j = 1:length(TheFiles)
BaseFileName = TheFiles(j).name;
FullFileName = fullfile(FullDirectory, BaseFileName);
delete(FullFileName);
end
end
end
0 Kommentare
Akzeptierte Antwort
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Search Path 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!