首页 > 解决方案 > Matlab跳过子文件夹

问题描述

我有一个包含顺序子文件夹 000001_wd、000002_wd、...的文件夹,我正在其中读取包含在名为“plane.txt”的文件中的数据。一些子文件夹不包含该文件。我希望在 for-if else 循环中跳过它们,但它无法打开文件。

尝试更改或添加路径,但似乎没有任何效果

workdir = 'D:\wass\test\output_925\';
cd(workdir)
data_frames = [1:1:37];

nframes = numel(data_frames);
V = zeros(nframes,3);
times = zeros(nframes,1);
ii=1;
prev = cd(workdir);
for frame = data_frames
    fprintf('Processing frame %d\n',frame);
    wdir = sprintf( '%s%06d_wd/', workdir, frame);
    cd(wdir)
     if exist('plane.txt')            
        plane_data = importdata([wdir,'plane.txt']);
        times(ii) = double(ii-1)/fps;
     else
        times(ii) = double(ii-1)/fps;
     end
    ii=ii+1;

end
cd(prev);

fprintf('Saving data...\n');

我想继续循环直到最后一个子文件夹。是否因为我要跳过的文件位于序列的子文件夹中而遗漏了什么?

标签: matlabdirectoryskip

解决方案


该语句exist('plane.txt')测试以查看文件“plane.txt”是否存在于当前目录中。如果是,则读取wdir子目录中的文件。显然,您还没有测试文件是否存在。

我将通过读取 try/catch 块中的数据来简化您的代码:

workdir = 'D:\wass\test\output_925\';
data_frames = 1:37; % <- don't use square brackets here, they're useless
nframes = numel(data_frames);
times = zeros(nframes,1);
for ii=1:nframes
    frame = data_frames(ii);
    fprintf('Processing frame %d\n',frame);
    wdir = sprintf( '%s%06d_wd/', workdir, frame);
    try
        plane_data = importdata([wdir,'plane.txt']);
        % do something with plane_data here...
    catch
        % ignore error
    end
    times(ii) = double(ii-1)/fps;
end
% ...

请注意,我从未使用过cd. 您无需更改目录即可读取数据,最好不要这样做。该importdata语句使用绝对路径,因此当前目录是什么并不重要。


另一种方法涉及获取所有匹配文件的列表'D:\wass\test\output_925\*\plane.txt'

files = dir(fullfile(workdir, '*', 'plane.txt'));
for ii=1:numel(files)
   file = fullfile(files(ii).folder, files(ii).name);
   plane_data = importdata(file);
   % do something with plane_data here...
end

推荐阅读