Check if file directory exists, else create it

25 次查看(过去 30 天)
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

采纳的回答

Bruno Luong
Bruno Luong 2024-10-8
mkdir(FullDirectory)
rather than
mkdir FullDirectory

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Search Path 的更多信息

产品


版本

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by