How to access all subdirectorie?

27 ビュー (過去 30 日間)
MINA
MINA 2018 年 3 月 6 日
コメント済み: MINA 2018 年 3 月 6 日
I want to find all subfolders in a folder. I know how to do it for one step but I want to do it recursively until it finds all sub-subdirectories. Example: I am at 'M:\F1' . And suppose I have F1_1 and F1_2 folders in there which I can have access with the following code
files = dir('M:\F1')
% Get a logical vector that tells which is a directory.
dirFlags = [files.isdir] & ~strcmp({files.name},'.') & ~strcmp({files.name},'..')
% Extract only those that are directories.
subFolders = files(dirFlags)
I have another folder in F1_1 called F1_1_1 and one folder in that called F1_1_1_1. How can I recursively find the path to these two folders, i.e.,
M:\F1\F1_1_1
M:\F1\F1_1_1\F1_1_1_1
  2 件のコメント
Elias Gule
Elias Gule 2018 年 3 月 6 日
The keyword here is recursively... so wrap your code in a function that accepts a string input. This input should be the directory that you want to traverse.
All you need to do now, is extract the path string of each directory in your 'subFolders' variable and pass that as input to your function.
Don't panic! You surely do know what you're doing.
MINA
MINA 2018 年 3 月 6 日
Thanks for the answer.

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

採用された回答

Fangjun Jiang
Fangjun Jiang 2018 年 3 月 6 日
Use dir(fullfile('M:\F1','**/*.*')). It will list everything in the folder and all sub-folders.

その他の回答 (3 件)

Paul Shoemaker
Paul Shoemaker 2018 年 3 月 6 日
編集済み: Paul Shoemaker 2018 年 3 月 6 日
Newer version of Matlab allow dir to operate recursively. Simply modify your original dir call like so:
files = dir(['M:' filesep 'F1' filesep '**/*.*']);
Then do your filtering on dirFlags as you've done. Voila!
Note: If you check out the help for dir you'll see other techniques to filter in different ways, such as only searching one level down.
Paul Shoemaker

Elias Gule
Elias Gule 2018 年 3 月 6 日
See this for an example.

MINA
MINA 2018 年 3 月 6 日
I also found to do the following
dirs = regexp(genpath('M\F1'),['[^;]*'],'match');

カテゴリ

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