Matlab遍历文件夹及子文件夹下某个文件,返回元胞数组,为后续循环索引文件提供支持
- 实现目的:
自动遍历某个文件夹及该文件夹下子文件夹的某个文件/某个文件类型的路径,并存储所有该文件的路径于元胞数组中,为后续方法体循环提供支持。
clc;clear;
maindir = 'C:\Users\Administrator\Desktop\sa\data';
subdir = dir( maindir ); % 确定子文件夹
filePath = {};
for i = 1 : length( subdir )
if( isequal( subdir( i ).name, '.' ) || isequal( subdir( i ).name, '..' ) || ~subdir( i ).isdir ) % 如果不是目录跳过
continue;
end
subdirpath = fullfile( maindir, subdir( i ).name, '*.nc' );
ncFile = dir( subdirpath );
for j = 1 : length( ncFile )
ncPath = fullfile( maindir, subdir( i ).name, ncFile( j ).name);
end
count = length(filePath);
filePath{count+1} = ncPath;
end
实验结果
上述代码展示了寻找主目录以及主目录下子文件夹下的.nc文件,并返回所有nc文件的路径,存放于元胞数组filePath中,后续需要对每个nc文件操作时,直接索引元胞数组中的路径即可。