1、获取第一层文件夹下的所有文件夹以及数据信息结构体。例如:主路径是SourcePath可以通过相对路径代码cd(SourcePath);File1NameFormation=dir('*.')获取当前路径下所有文件夹信息并且将文件夹信息保存在File1NameFormation中。也可以使用绝对路径:File1NameFormation=dir('SourcePath\*.');对于需要列出什么类型的文件可以通过将'*.'改成'*.xxx';其中XXX为类型文件扩展名
2、对路径扩展进行计数,循环进行分文件夹读取File1Number=numel(File1NameFormation);或者File1Number=size(File1NameFormation,1);通过获取当前文件夹中有多少层文件夹。
3、对得到的文件夹通过计数进行循环,进入次文件夹一次继续读取文件。但是这里需要注意的是,如果是文件夹需要从第三个文件夹读取,因为'.'和'..'一个为当前文件夹一个为上一层文件夹,所以需要从第三个文件读取,可以通过第二个返回上一层文件夹。
4、可以发现进入子文件后就进入循环了,返回了第一步。在这里可以整合所有的代码cd(SourcePath)File1NameFormation=dir(&垆杪屑丝#39;*.');File1Number=numel(File1NameFormation)for LoopFile1Number=3:File1Number NowPath=fullfile(SourcePath,File1NameFormation(LoopFile1Number).name......................end回顾整个过程,重复写的代码很多,在这里我们可以通过运用递归的思维写一个读取数据代码。
5、这里通过循环来写读取文件函数。function ReadFile(MainPath,FileType,FileLayer)%%%%%%%%%%%鬈熵痼霄%%%%MainPath为主路径,FileType为需要读取的文件类型,FileLayer为文件类型在哪一层文件下cd(MainPath);if(FileLay>=0)PathFileFormation=dir('*.');PathNumber=numel(PathFileFormation);for LoopPathNumer=3:PathNumber Path=fullfile(MainPath,PathFileFormation(LoopPathNumber).name); ReadFile(Path,FileType,FileLayer-1)endelsePathFileFormation=dir('FileType');PathNumber=numel(PathFileFormation);for LoopPathNumer=3:PathNumber Path=fullfile(MainPath,PathFileFormation(LoopPathNumber).name)endend