Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over folders?

I have the code like this:

          myFolder='C:\Users\abe7rt\Desktop\dat\1';
          filePattern=fullfile(myFolder, '*.txt');
          txtFiles=dir(filePattern); 

Now, dat is a folder that contains "1,2,3" folders and each one of these folders contains 20 TXT files. The previous code is able to get the txt files from 1 folder. Now my question is: is there a way to loop over all the directories?

like image 508
mecaeng Avatar asked Feb 20 '26 14:02

mecaeng


1 Answers

Yet another possibility, using the apache commons library that comes with MATLAB:

function fileNames = findAllFiles(directory, wildcardPattern)

    import org.apache.commons.io.filefilter.*;
    import org.apache.commons.io.FileUtils;
    import java.io.File;

    files = FileUtils.listFiles( File(directory),...
                                 WildcardFileFilter(wildcardPattern),...
                                 FileFilterUtils.trueFileFilter());

    fileNames = cellfun(@(f) char(f.getCanonicalPath()),...
                        cell(files.toArray()),...
                        'uniformOutput', false);
end

Use e.g. as:

files = findAllFiles('C:\Users\abe7rt\Desktop\dat', '*.txt')

If you'd like to also apply a pattern on the directory-names in which the search should descend, you can simply replace the FileFilterUtils.trueFileFilter() with another WildcardFileFilter.

like image 131
sebastian Avatar answered Feb 22 '26 05:02

sebastian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!