matlab - 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');
我想继续循环直到最后一个子文件夹。是否因为我要跳过的文件位于序列的子文件夹中而遗漏了什么?
解决方案
该语句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
推荐阅读
- regex - 正则表达式匹配语句
- c# - 使用 Visual Studio 2019 构建现有 sln 失败
- elasticsearch - 全局聚合没有考虑弹性搜索中的所有文档
- mongodb - 元数据库日期计算
- javascript - 如何使子菜单项出现,而父母在全屏覆盖菜单中保持不变?
- c# - 如何合并列表中的多个连续值?
- java - 将 REST api 添加到 Vaadin
- java - Robolectric 测试中 Android Activity 中的模拟字段
- javascript - 如何更新几何中的重复顶点?三个js
- sequelize.js - 通过 Sequelize 在 MySQL 中将 1|2|3 存储为整数