How to skip a file in reading a series of csv files using csvread?
2 次查看(过去 30 天)
显示 更早的评论
Hi.
I am reading a large number of data from say, 100 csv files using csvread. But some of these files (say 10) have nonnumeric values/characters etc. which cannot be read by csvread. This gives an error and stops the code. I do not necessaruly need those faulty files. How can I ask MATLAB to, if encountered such an error, ignore that whole file and continue reading the rest? So for example if file number 12 is faulty, the file 13 will be read as 12 and so on?
This is the error for reading the faulty files:
"Mismatch between file and format character vector. Trouble reading 'Numeric' field from file ......"
and this is the loop:
for i = 1: 100
fileID = sprintf([FileName,'_%02d.csv'], i);
M = csvread(fileID,3,0);
end
Thanks!
0 个评论
采纳的回答
David K.
2019-9-17
One method, though it may be one that is often advised against, is to use a try catch block around the code. When an error occurs inside the try block the catch code will be executed and the loop will continue.
for i = 1: 100
fileID = sprintf([FileName,'_%02d.csv'], i);
try
M = csvread(fileID,3,0); % line that will cause an error you dont care about
catch
warning(strcat('This file failed: ', num2str(i))) % Some warning message to let you know
end
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!