delete files in folder with different endings

12 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2021-3-8
编辑:Stephen23 2021-3-8
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 个评论
Patrick Benz
Patrick Benz 2021-3-8
As i said above, this was just my approach.
Thanks for answering with more robust and faster way.

请先登录,再进行评论。

更多回答(1 个)

Patrick Benz
Patrick Benz 2021-3-8
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

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by