2012-01-05 141 views

回答

48

使用isdir分離子目錄和文件:

d = dir(pathFolder); 
isub = [d(:).isdir]; %# returns logical vector 
nameFolds = {d(isub).name}'; 

然後,您可以刪除...

nameFolds(ismember(nameFolds,{'.','..'})) = []; 

你不應該做nameFolds(1:2) = [],因爲從根目錄dir輸出不包含這些點文件夾。至少在Windows上。

7

這非常雨衣和所有一行:

dirs = regexp(genpath(parentdir),['[^;]*'],'match'); 

解釋: genpath()是吐出parentdir的所有子文件夾在單個文本行,由分號分隔的命令。正則表達式函數regexp()在該字符串中搜索模式,並返回選項:'匹配'到模式。在這種情況下,模式是任何字符而不是分號=`[^;],在一行中重複一次或多次= *。因此,這將搜索字符串並將所有不是分號的字符分組爲單獨的輸出 - 在本例中爲所有子文件夾目錄。

+2

此命令列出的主要文件夾和子文件夾 - 這不是什麼提問者通緝。 – ioanwigmore 2013-10-21 12:05:25

+1

這個答案幫助我快速列出所有子目錄。謝謝。 – axs 2014-02-25 16:48:03

+1

非常好的解決方案!但是你需要記住''genpath'函數設計用來生成搜索路徑,所以它跳過了一些特定的文件夾。請參閱[doc](http://www.mathworks.com/help/matlab/ref/genpath.html)。 – yuk 2014-05-20 15:54:22

0

以下代碼片斷僅返回子文件夾的名稱。

% `rootDir` is given 
dirs = dir(rootDir); 
% remove `.` and `..` 
dirs(1:2) = []; 
% select just directories not files 
dirs = dirs([obj.dirs.isdir]); 
% select name of directories 
dirs = {dirs.name}; 
0

,並有效地重新使用在不同的場景中的提供的第一個解決方案我做了一個函數出來的:

function [ dirList ] = get_directory_names(dir_name) 

    %get_directory_names; this function outputs a cell with directory names (as 
    %strings), given a certain dir name (string) 
    %from: http://stackoverflow.com/questions/8748976/list-the-subfolders- 
    %in-a-folder-matlab-only-subfolders-not-files 

    dd = dir(dir_name); 
    isub = [dd(:).isdir]; %# returns logical vector 
    dirList = {dd(isub).name}'; 
    dirList(ismember(dirList,{'.','..'})) = []; 

end 
相關問題