Check if file directory exists, else create it
23 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Daniel van Huyssteen
le 8 Oct 2024
Réponse apportée : Bruno Luong
le 8 Oct 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 commentaires
Réponse acceptée
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Search Path dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!