如果批量读取一个文件夹(为叙述方便起见,该文件夹命名为2012)内的txt类型文件,这些文件是储存在这个文件夹的子文件夹里,即2012文件夹里面包含了文件夹6、7(6、7表示6月、7月),6、7文件夹里面又有文件夹1到30(表示1到30天),文件夹1到30里面各包含一个文件夹dq,文件夹dq里面包含的才是txt文件(文件夹dq只包含一个txt文件),请问如何用M文件编程,批量读取这些txt文件。感觉好难啊!!! |
最佳答案
基本原则是,每遇到一层文件夹中有多个文件(夹),就需要用一层循环。所以在你的程序中: 1、由用户指定2012这个文件夹 2、用dir命令获取2012下面的所有文件夹,即6,7 (第一层循环) 3、对6和7分别用dir命令找出其下的所有的子文件夹,即1-30(第二层循环) 4、在第二层循环内部,把之前找到的各子文件夹名拼在一起,后面再加入dq,即得每一个txt文件所在路径K 5、用dir找到K下的txt文件名,读取之即可。 main = 'C:\...\2012\' sub1 = dir(main); sub1([~sub1.isdir]) = []; % remove all non-directory entries sub1 = sub1(3:end); % remove . and .. for i = 1:length(sub1) sub2 = dir([main sub1(i).name]); % 以下两步同sub1 for j = 1:length(sub2) thispath = [main '\' sub1(i) '\' sub2(j) '\dq\']; txtname = dir([thispath '*.txt']); fullname = [thispath txtname(1)]; % fullname contains the fullpath to one txt file. Now you can use whatever function to read it READFILE(fullname); ... ... |
5 条回复
基本原则是,每遇到一层文件夹中有多个文件(夹),就需要用一层循环。所以在你的程序中: 1、由用户指定2012这个文件夹 2、用dir命令获取2012下面的所有文件夹,即6,7 (第一层循环) 3、对6和7分别用dir命令找出其下的所有的子文件夹,即1-30(第二层循环) 4、在第二层循环内部,把之前找到的各子文件夹名拼在一起,后面再加入dq,即得每一个txt文件所在路径K 5、用dir找到K下的txt文件名,读取之即可。 main = 'C:\...\2012\' sub1 = dir(main); sub1([~sub1.isdir]) = []; % remove all non-directory entries sub1 = sub1(3:end); % remove . and .. for i = 1:length(sub1) sub2 = dir([main sub1(i).name]); % 以下两步同sub1 for j = 1:length(sub2) thispath = [main '\' sub1(i) '\' sub2(j) '\dq\']; txtname = dir([thispath '*.txt']); fullname = [thispath txtname(1)]; % fullname contains the fullpath to one txt file. Now you can use whatever function to read it READFILE(fullname); ... ... |
Powered by Discuz! X3.4
© 2001-2024