Read different folders by changing path with for loop
显示 更早的评论
Hi. I have a code that takes as reference the folder 'DATA 1' containing some .jpg images:
P = 'C:\Users\Alberto\Desktop\GLOBAL\DATA1'; % folder DATA 1
However, inside the folder 'GLOBAL' there are multiple folders: 'DATA1', DATA 2', etc., and some folders may be missing, for example 'DATA 3' (but have the folder 'DATA 4').
I want to automatically apply my code so that, for each for loop, it can refer to a different folder, for example:
P = 'C:\Users\Alberto\Desktop\GLOBAL\DATA2'; % folder DATA 2
P = 'C:\Users\Alberto\Desktop\GLOBAL\DATA3'; % folder DATA 3
and so on...
采纳的回答
更多回答(1 个)
Khushboo
2022-11-7
Hello,
You can refer to the following script to do this. I am basically looping through all the DATA X folders and then looping through all the folders within each DATA X (such that X=1,2,3,..):
D = ''; % specify the path to the main directory (one folder before DATA X)
S = dir(fullfile(D,'*'));
N = setdiff({S([S.isdir]).name},{'.','..'}); % list the subfolders of D (lists different DATA X folders where X = 1,2, and so on)
% loop through all the DATA X folders
for i = 1:numel(N)
T = dir(fullfile(D,N{i},'*')); % get all the subfolders in the current directory (DATA X)
T = T(3:end); % to exclude the '.' and '..' directories created
% rename the files within the DATA X folder
for fileNo = 1:length(T)
currFile = T(fileNo);
oldname = fullfile(currFile.folder,currFile.name);
newname = [fullfile(currFile.folder,'CorrectedExample') currFile.name(end)];
movefile(oldname,newname);
end
end
Hope this helps!
2 个评论
Stephen23
2022-11-7
T = T(3:end); % !!! Buggy code !!!
This topic has been discussed extensively on this forum:
As Walter Roberson wrote in that last link: "In short: if your code assumes that '.' and '..' are the first two entries in a directory, your code has a bug (even in MS Windows). If your code assumes that directory entries are returned in any sorted order, your code has a bug (in all OS.)"
Khushboo
2022-11-7
Oh okay, thankyou for pointing it out. The code seemed to work in my case (MacOS) but yeah it will not be correct when the order in which directories are returned is different.
Thankyou for pointing it out!
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!