MATLAB Answers

Steven
0

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

Asked by Steven
on 17 Sep 2019
Latest activity Commented on by Steven
on 18 Sep 2019
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 Comments

Sign in to comment.

Tags

1 Answer

Answer by David K.
on 17 Sep 2019
 Accepted Answer

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

  1 Comment

Thanks. It does the job :)

Sign in to comment.