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

522 ビュー (過去 30 日間)
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, - https://www.mathworks.com/matlabcentral/fileexchange/32036-dirwalk-walk-the-directory-tree , 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
>>fold2
>>files
>>Dir 2
...etc

採用された回答

Guillaume
Guillaume 2018 年 11 月 14 日
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
  5 件のコメント
Michael
Michael 2024 年 2 月 3 日
For me I had to swap '**\*.*' for '**/*.nii' since on linux I got
Error using dir
Characters adjacent to a ** wildcard must be file separators.
Steven Lord
Steven Lord 2024 年 8 月 20 日
For me I had to swap '**\*.*' for '**/*.nii' since on linux
You could adapt Guillaume's fullfile usage. Since the MATLAB sessions used by MATLAB Answers to evaluate code run on Linux, it will automatically use the appropriate filesep to assemble the directory path.
rootdir = 'ThisIsMyRootDirectory';
filesep
ans = '/'
directoryName = fullfile(rootdir, '**', '*.*')
directoryName = 'ThisIsMyRootDirectory/**/*.*'

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by