Check if file directory exists, else create it
조회 수: 23 (최근 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
댓글 수: 0
채택된 답변
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Search Path에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!