delete files in folder with different endings
12 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Patrick Benz
il 8 Mar 2021
Commentato: Patrick Benz
il 8 Mar 2021
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
0 Commenti
Risposta accettata
Stephen23
il 8 Mar 2021
Modificato: Stephen23
il 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
Più risposte (1)
Vedere anche
Categorie
Scopri di più su File Operations in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!