Error using rmdir for deleting slprj folder
7 次查看(过去 30 天)
显示 更早的评论
I would like to know why this rmdir comand does not work properly, this is the script made for deleting some variables and also the folder.
% % % %
current_path = pwd;
% %
%;
for k=1:64
FolderName=['CMkb1_',num2str(k)];
ruta=cd([current_path,'\',FolderName]);
delete Ib.mat
delete Ic.mat
delete IL.mat
delete Is.mat
delete kb1.mat
rmdir(ruta, "slprj\")
end
Error using rmdir
'slprj\' is an invalid option.
Error in Eliminar_mat_enSerie (line 17)
rmdir(ruta, "slprj\")
0 个评论
采纳的回答
Image Analyst
2023-5-20
You cannot delete a folder if somebody is using it or looking at it, for example if you cd'd to that folder in MATLAB, have it open in File Explorer, have some document living there open in some program such as Excel, etc.
Don't use cd in your code. See the FAQ: https://matlab.fandom.com/wiki/FAQ#Where_did_my_file_go?_The_risks_of_using_the_cd_function.
Try this more robust, but untested, code:
currentFolder = pwd;
% Find out how many subfolders there are in the folder.
filePattern = fullfile(currentFolder, 'CMkb1*');
fileList = dir(filePattern);
numFolders = numel(fileList)
if numFolders == 0
warningMessage = sprintf('No CMkb1* subfolders found under "%s"', currentFolder);
uiwait(warndlg(warningMessage));
else
% Delete files in subfolders, then the subfolder itself.
for k = 1 : numFolders
thisBaseFolderName = ['CMkb1_', num2str(k)];
thisFullFolderName = fullfile(currentFolder, thisBaseFolderName);
if ~isfolder(thisFullFolderName)
% Skip this one if the folder does not exist.
fprintf('Folder "%s" not found.\n', thisFullFolderName);
continue;
end
% Delete the 5 .mat files.
fileToDelete = fullfile(thisBaseFolderName, 'ib.mat');
if isfile(fileToDelete)
delete(fileToDelete)
end
fileToDelete = fullfile(thisBaseFolderName, 'Ic.mat');
if isfile(fileToDelete)
delete(fileToDelete)
end
fileToDelete = fullfile(thisBaseFolderName, 'IL.mat');
if isfile(fileToDelete)
delete(fileToDelete)
end
fileToDelete = fullfile(thisBaseFolderName, 'Is.mat');
if isfile(fileToDelete)
delete(fileToDelete)
end
fileToDelete = fullfile(thisBaseFolderName, 'kb1.mat');
if isfile(fileToDelete)
delete(fileToDelete)
end
% You could also use a loop to delete all .mat files, or just use a wildcard to delete them all in one shot.
% Now remove the folder itself. I think the folder must be totally empty.
try
rmdir(thisFullFolderName)
fprintf('Folder "%s" removed.\n', thisFullFolderName);
catch ME
% Keep going even if this didn't work for this one folder.
end
end
end
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Sources 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!