MATLAB: Error that file not found

csvreadfscanfopen

clear all; close all;
files = dir('/Users/filepath/*.csv'); % need to change the directory
fileID = fopen('csvfilelistohm.txt'); % need to have a txt. file with all the file names
num_files = length(files);
for i = 1:num_files
name{i} = fscanf(fileID,'%s\n',1);
mydata = csvread(name{i},12,1,[12,1,61,17]);
I am having problems running this code (there is much more following this section but it is the part I can't get past). Admittedly it was not written by me, but I have gotten it to run before. The error message I am receiving is
"Error using csvread (line 35) File not found. Error in binned_cos_scalar_ohmaug30 (line 9) mydata = csvread(name{i},12,1,[12,1,61,17]);"
Any ideas how I can make the code work? What the program usually does is reads through about 1599 .csv files separately, brings in the relevant data, plots it, saves the figure, then closes it and moves on to the next .csv file in the list. It seems some days it works fine and others Matlab doesn't like this first part of the code. Maybe there is a better way to write it out?

Best Answer

Please attach 'csvfilelistohm.txt'. Apparently there is a string in there that is a filename but without an extension. This code is not robust at all. But what is worse is that the name variable will not change on each iteration - not that it has to since you could overwrite "name" but it should be different. If you don't need to store all the names (or the only one that you are reading actually), then just overwrite it:
for k = 1 : num_files % Don't use i as an iterator variable.
% Get a new filename from the file. (Won't happen though!)
thisFileName = fscanf(fileID,'%s\n',1);
% It's presumably a csv file, so check if it's actually there.
[folder, baseFileName, extension] = fileparts(thisFileName);
if ~exist(thisFileName)
warningMessage = sprintf('WARNING: file does not exist:\n%s', thisFileName);
uiwait(warndlg(warningMessage));
continue;
end
% If we get to here, the file exists.
% Make sure it's a CSV file.
if ~strcmpi(extension, '.csv')
continue;
end
% Read file into an array.
mydata = csvread(thisFileName,12,1,[12,1,61,17]);
% Now do something with mydata.
end