delete files in folder with different endings

조회 수: 12 (최근 30일)
Patrick Benz
Patrick Benz 2021년 3월 8일
댓글: Patrick Benz 2021년 3월 8일
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