Error using xlsread and csvread

374 Views Asked by At

I have a folder with many .csv files. I need to load one file at at time and perform some operations. I tried loading files in a loop using the csvread and xlsread command but it does not work. My files are in a .csv format but csvread does not read it as my files have text and numbers. Hence I used `xlsread' but I get error saying the file.csv could not be found. I am unsure what the problem is.I use the following code to read files in a loop:

  files=dir('foldername');
  N=length(files);
  for i=1:N
      thisfile=xlsread(files(i).name);
  end

Variable files is read as a structure and it displays filename, filelocation,bytes and dates. Should I convert to an array in order to read the contents of the file?

1

There are 1 best solutions below

11
gnovice On

The output from dir will include the entries . and .., along with any other subfolders in 'foldername', so you will want to remove those first. You can do that like so:

files = dir('foldername');
files = files(~[files.isdir]);

Or, as Vahe Tshitoyan suggests, you can collect only the .csv files like so:

files = dir('foldername\*.csv');

If you have any other files you don't want to process in the folder, you should definitely use the second approach.

If you're getting an error saying the file cannot be found in your call to xlsread it probably means you need to specify the full path to the file instead of just the file name. You can use the 'folder' field of the structure returned by dir and pass that along with the file name to fullfile, like so:

for i = 1:N
  thisfile = xlsread(fullfile(files(i).folder, files(i).name));
  % Subsequent processing
end