目录
前言
一、讲下思路
二、MATLAB代码
总结
前言
Up主萌新一枚,望各路大神多多指教!第一篇csdn就写一下最近工作中碰到的一个小问题,就是需要在处理文件类型转换或者做数据处理任务时研究的一个小tips,即本文所讲的关于如何使用MATLAB读取给定路径下的所有特定类型文件名称。
一、讲下思路
- 在给定了所涉及的文件夹在本地的绝对路径的情况下,MATLAB支持遍历该路径下所有的成员,包括每一个文件以及子文件夹。
- 在遍历路径下每个成员时,如果该成员是一个单个的文件,则截取其后缀名与我们需要的目标后缀名进行比较,MATLAB支持以正则表达式 regexp() 对所需要的字符串进行查找。
- 如果遍历到的成员为一个子文件夹,那么此时最有效的方式自然而然就是迭代!可以想象一下,每一次迭代都会进入一个子文件夹一直到最后一层子文件夹路径,再一层层的跳出来,就不会漏掉目标路径下的任何一个角落。
- 根据需要提取相应的信息,我的项目是需要提取子文件夹名称,所有目标文件的路径和名称,全部以字符串数组的形式存储,详见代码。
- 这里需要注意的是,MATLAB使用dir命令读取目标路径下的所有成员时,会读取到两个系统默认文件夹,名字分别是 ‘.’ 和 ‘..’,对你没看错,就是一个点和两个点 0.0,这个是需要舍弃掉的,不然也没啥用。
二、MATLAB代码
%%
function [all_file_name, all_file_path, all_folders_name] = file_extraction(given_path, required_suffix)
% Initialize the output arrays
all_file_name = {};
all_file_path = {};
all_folders_name = {};
% Read the given path, store into a struct
path_objects = dir(given_path);
% traverse all the objects in the given path
for i = 1:1:length(path_objects)
% if this object is a folder
if isfolder(fullfile(given_path,path_objects(i).name))
% if this folder is not the system default folder
if ~strcmp(path_objects(i).name,'.') && ~strcmp(path_objects(i).name,'..')
% do the iteration
[sub_path,~,file_name_sub] = file_extraction(fullfile(given_path,path_objects(i).name),required_suffix);
% if the sub path is not an empty directory
if ~isempty(sub_path)
% gather the required information
all_file_name = [all_file_name;file_name_sub];
all_file_path = [all_file_path;sub_path];
all_folders_name = [all_folders_name;path_objects(i).name];
end
end
else
% use Regular expression to locate the suffix
index = regexp(path_objects(i).name,'\.');
captured_suffix = path_objects(i).name((index(end)+1):end);
% if the suffix matches, gather the required information
if ~isempty(find(strcmp(required_suffix,captured_suffix),1))
all_file_name = [all_file_name;fullfile(given_path,path_objects(i).name)];
all_file_path = [all_file_path;sub_path];
end
end
end
end
总结
以上就是今天想要分享给大家的内容,使用迭代法读取指定本地绝对路径下的所有特点类型的文件,如有不对的地方欢迎大佬们指正!