MATLAB Answers


Looping over folders, skipping a folder if a file is present

Asked by Clifford Shelton on 3 Feb 2013

I have code that executes a for loop through a folder and all of its subdirectories. My questions is how do I write the code in order to :

A.) check if a file is present within the folder in the for loop, and then

B.) skip that folder containing the file IF the file is present.

Here is the code i have been fumbling with so far:

mainFolder = 'c:\data';
subdirs = dir(mainFolder);
%This filters out all the items in the main folder that are not directories
subdirs(~[subdirs.isdir]) = [];
%And this filters out the parent and current directory '.' and '..'
tf = ismember( {}, {'.', '..'});
subdirs(tf) = [];
numberOfFolders = length(subdirs);
% %Here i am creating the variables to iterate over the date folders
% dates = fieldnames(subdirs);
% for loopIndex = 1:numel(dates)
%     stuff = subdirs.(dates{loopIndex})
% end
% Here I begin the for loop.  My aim is to tell the program to skip all %the folders that contain the file "Present.txt"
for K = 1: numberOfFolders
thissubdir = subdirs(K).name;
subdirpath = [mainFolder '\' thissubdir];
%This is WRONG WRONG WRONG... help please?
  if exist('Present.txt') == 1

Thanks for all the help!



No products are associated with this question.

2 Answers

Answer by Image Analyst
on 3 Feb 2013
Edited by Image Analyst
on 3 Feb 2013
 Accepted answer

Since you aren't calling cd for every subdir (that's good by the way), you need to construct the full file name.

fullfileName = fullfile(subdirpath, 'Present.txt');
if exist(fullfileName , 'file') == 2
  % Then the file exists, skip the rest of the code in the loop.

  1 Comment

Eternal Thanks!

Answer by Cedric Wannaz
on 3 Feb 2013
Edited by Cedric Wannaz
on 3 Feb 2013

EDIT: jump to the solution provided by Image Analyst, it is better.

You should use fullfile() for building subdirpath. Now there are several solutions for you to check the existence of the file; but to stick to what you already used, you could do something like:

subdircontent = dir(subdirpath) ;
if ismember('Present.txt', {})

  1 Comment

Jan Simon
on 3 Feb 2013

ismember has a large overhead, e.g. a sorting or the strings. Therefore this is more efficient:

if any(strcmp('Present.txt', {}))

But I admit, it will hardly make a program noticably faster...

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!