delete files in folder with different endings

12 views (last 30 days)
Hey guys,
I am trying to delete several files with different endings in a folder.
the problem is that there are some files that should not be deleted. I want to delete everything but ".odb", ".txt". ".py" and ".m".
I tried it like this
FolderName=pwd;
FolderDir = dir(FolderName);
Name = {FolderDir.name};
Name(strcmp(Name, '.')) = [];
Name(strcmp(Name, '..')) = [];
for iName = 1:length(Name)
aName = fullfile(FolderName, Name{iName});
if (aName(:,((end-3):end)) == '.odb' || aName(:,((end-3):end)) == '.txt' || aName(:,((end-2):end)) == '.py' || aName(:,((end-1):end)) == '.m')
continue
else
try
delete(aName);
catch
warning('Cannot delete %s', aName);
end
end
end
When I only use the first argument in the If line it works just fine. With multiple arguments I get an Error
"Operands to the || and && operators must be convertible to logical scalar values.
Error in Loeschtest (line 8)
if (aName(:,((end-3):end)) == '.odb' || aName(:,((end-3):end)) == '.txt')% || aName(:,((end-2):end)) == '.py' || aName(:,((end-1):end)) == '.m')"
Can anyone help me with the error or is there a better way do delete the files? I got 15 files with 13 different endings and this code shall become part of a bigger project which creates these 15 files in a loop of 50 iterations. Thats why I want to delete the unnecessary files at the end of every iteration

Accepted Answer

Stephen23
Stephen23 on 8 Mar 2021
Edited: Stephen23 on 8 Mar 2021
K = [".odb", ".txt", ".py", ".m"];
D = pwd;
S = dir(fullfile(D,'*.*'));
S = S(~[S.isdir]); % files only
for k = 1:numel(S)
F = S(k).name;
[~,~,E] = fileparts(F)
if ismember(E,K)
try
delete(fullfile(D,F));
catch
warning('Cannot delete %s',F);
end
end
end
Another (possibly more efficient) approach would be to use SETDIFF to get an array of all existing file extensions that you do NOT wish to keep, and then loop over that list, generating a suitable filename string for DELETE including the wildcard character. That lets the OS delete the files as quickly as it can. Something like this (untested):
[~,~,E] = fileparts({S.name});
X = setdiff(unique(E),K); % file extensions to delete
for k = 1:numel(X)
F = sprintf('*%s',X{k});
delete(fullfile(D,F))
end
  1 Comment
Patrick Benz
Patrick Benz on 8 Mar 2021
As i said above, this was just my approach.
Thanks for answering with more robust and faster way.

Sign in to comment.

More Answers (1)

Patrick Benz
Patrick Benz on 8 Mar 2021
I just answered the question myself.
for later use:
if (aName(:,((end-3):end)) == ".odb" || aName(:,((end-3):end)) == ".txt" || aName(:,((end-2):end)) == ".py" || aName(:,((end-1):end)) == ".m")
end
replace ' with " and everything is working like it should

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!