How to skip a file in reading a series of csv files using csvread?

2 views (last 30 days)
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!

Accepted Answer

David K.
David K. on 17 Sep 2019
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

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!