How to recursively go through all directories and sub directories and process files?

644 views (last 30 days)
So I have a single directory with sub directories and sub directories and then files (its a mess). I want to go to each folder at end ( I dont care about directories) and process the files in it (be it .txt .jpg etc). I kinda got a way to list all folders using the dirwalk function from here, - , but I don't know two things. How to figure out if a path (the function outputs all possible paths, thats what i understood) is not directory with sub directories, but a directory with images or text files, so I can process them. After choosing a path, I need to figure out how to loop through files. Or is there an easier way I'm missing? any advice would be appreciated!
Example of direc structure:
Main Directory>
>> Dir 1
>> fold1
>>txt files
>>Dir 2

Accepted Answer

Guillaume on 14 Nov 2018
Since R2016b, dir can recurse through subdirectories using **. So it's as simple as:
rootdir = 'C:\somewhere\somedirectory';
filelist = dir(fullfile(rootdir, '**\*.*')); %get list of files and folders in any subfolder
filelist = filelist(~[filelist.isdir]); %remove folders from list
Daniel Poiesz
Daniel Poiesz on 9 Aug 2021
I just learned the leading '**\' is required for recursion and '*.mat' would only find files in the root directory.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!