MATLAB 查找文件夹(包括子文件夹)下特定类型的文件

简介

在对文件查找,遍历等操作时,经常遇到对文件夹下所有的特地类型文件汇总或者遍历等批量操作,首先就需要对文件夹下或者文件夹下包含的子文件夹下的文件全部收集,采用下面提供的函数即可:

函数

函数输入为:需要搜索的路径,需要搜索的文件扩展名(可同时对多种扩展名搜索)
例如:
ListPath = folder_search( pwd, {‘m’,‘p’})
即对当前文件夹下的m类型和p类型的文件搜索,并将搜索到的文件完整路径都放置在ListPath 这个cell数组变量中。
也可以对单个文件类型搜索,例如:
ListPath = folder_search( pwd, ‘m’)

源代码

% 搜索路径
function ListPath = folder_search( path_target, extension_target )
list_dir = dir( path_target );
ListPath = {   };
for i = 1:1:length( list_dir )
    if isdir( fullfile( path_target, list_dir( i ).name ) ) && ~strcmp( list_dir( i ).name, '.' ) && ~strcmp( list_dir( i ).name, '..' )
        ListPathSub = folder_search( fullfile(path_target, list_dir( i ).name), extension_target );
        if ~isempty( ListPathSub )
            ListPath = [ ListPath;ListPathSub ];
        end
    else
        idx_dot = regexp( list_dir( i ).name, '\.' );
        file_extension = list_dir( i ).name( ( idx_dot( end  ) + 1 ):end  );
        if ~isempty( find( strcmp( file_extension, extension_target ) ) )
            ListPath = [ ListPath;fullfile( path_target, list_dir( i ).name ) ];
        end
    end
end
end
    原文作者:AutoMarie
    原文地址: https://blog.csdn.net/qq_36320710/article/details/116742409
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞