相对于 Matlab 工作目录,我在'../../My_Dir'
有一个目录。此目录本身包含多个子目录。然后,每个子目录中都包含多个文件。
我想创建字符串的二维数组或矩阵。每行表示一个子目录。该行中的第一列是子目录本身的完整路径,其他列是该子目录中文件的完整路径。
谁能给我看一些可以帮助我实现这一点的代码?谢谢!
您可以先通过以下方式获取所有子文件夹
d = dir(pathFolder);
isub = [d(:).isdir];
subFolders = {d(isub).name}';
请注意,您还需要从中删除.
和..
:
subFolders(ismember(subFolders,{'.','..'})) = [];
然后使用(从这篇文章中)获取每个文件中的文件:
function fileList = getAllFiles(dirName)
dirData = dir(dirName); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
fileList = {dirData(~dirIndex).name}'; %'# Get a list of the files
if ~isempty(fileList)
fileList = cellfun(@(x) fullfile(dirName,x),... %# Prepend path to files
fileList,'UniformOutput',false);
end
subDirs = {dirData(dirIndex).name}; %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'}); %# Find index of subdirectories
%# that are not '.' or '..'
for iDir = find(validIndex) %# Loop over valid subdirectories
nextDir = fullfile(dirName,subDirs{iDir}); %# Get the subdirectory path
fileList = [fileList; getAllFiles(nextDir)]; %# Recursively call getAllFiles
end
end
要获取文件夹的完整路径:
d = dir(baseDir);
d(~[d.isdir])= []; %Remove all non directories.
names = setdiff({d.name},{'.','..'});
filesFullPath = names;
for i=1:size(names,2)
filesFullPath{i} = fullfile(baseDir,names{1,i});
end
Matlab... "thanks" for this s...
例如,假设我在'My_Dir'
中有三个子文件夹,分别称为'A'
(包含'a1.txt'
和'a2.txt'
),'B'
(包含'b1.txt'
)和'C'
(包含'c1.txt'
,'c2.txt'
和'c3.txt'
)。这将说明如何处理每个子文件夹中具有不同数量文件的案例......
对于 MATLAB 版本 R2016b 及更高版本,dir
函数支持递归搜索,允许我们收集文件列表,如下所示:
dirData = dir('My_Dir**.*'); % Get structure of folder contents
dirData = dirData(~[dirData.isdir]); % Omit folders (keep only files)
fileList = fullfile({dirData.folder}.', {dirData.name}.'); % Get full file paths
fileList =
6×1 cell array
'...My_DirAa1.txt'
'...My_DirAa2.txt'
'...My_DirBb1.txt'
'...My_DirCc1.txt'
'...My_DirCc2.txt'
'...My_DirCc3.txt'
作为替代方案,特别是对于早期版本,这可以使用我发布到 MathWorks 文件交换的实用程序来完成:dirPlus
。它可以按如下方式使用:
dirData = dirPlus('My_Dir', 'Struct', true, 'Depth', 1);
fileList = fullfile({dirData.folder}.', {dirData.name}.');
现在,我们可以按照您上面指定的方式格式化fileList
。首先,我们可以使用unique
来获取唯一子文件夹的列表和索引。然后,该索引可以与mat2cell
一起使用,diff
按子文件夹将fileList
分解为第二级单元数组封装:
[dirList, index] = unique({dirData.folder}.');
outData = [dirList mat2cell(fileList, diff([index; numel(fileList)+1]))]
outData =
3×2 cell array
'...My_DirA' {2×1 cell}
'...My_DirB' {1×1 cell}
'...My_DirC' {3×1 cell}