I am needing to loop through a whole folder of files, but I am struggling to figure out how to read/open the csv files once I have gotten this far:
% This counts the number of files that will need to be looped through, so
% pick the folder with all of the data desired to be run
source_dir = uigetdir([]);
d = dir([source_dir, '\*.csv']);
z = length(d);
%Get information about what's inside your folder.
myfiles = dir(source_dir);
%Get the filenames and folders of all files and folders inside the folder
%of your choice.
filenames = {myfiles(:).name}';
filefolders = {myfiles(:).folder}';
%Get only those files that have a csv extension and their corresponding
%folders.
csvfiles = filenames(endsWith(filenames,'.csv'));
csvfolders = filefolders(endsWith(filenames,'.csv'));
%Make a cell array of strings containing the full file locations of the
%files.
files = fullfile(csvfolders,csvfiles);
Filenames = string(filenames);
Filefolders = string(filefolders);

 Accepted Answer

Sebastian Thuné
Sebastian Thuné on 16 Sep 2020

0 votes

Hi,
Have you tried the csvread() command?

9 Comments

Hi,
I have tried the cvsread() command.
It gives me this what I have below. I am trying to index the Filenames so that I can do some sort of for loop eventually.
csvread(Filenames(4,1))
Error using csvread (line 35)
File not found.
The reason is that your files are in an array and when you use () your getting that cell instead of the string within it.
It worked for me when i ran:
csvread(files{1})
if you try to use filenames you dont have the whole path for the file and you have to make sure to cd() to the path of the files. Or just call the line above that i posted.
Hi Noah,
I think your MATLAB path is different from where your csv file is located. You can either move your file to your MATLAB path or change your MATLAB path to where your file is.
You are right Sebastian that does work. The problem I have now is that I realized that this line below does not take all of the files with csv at the end that are actually in the folder. It only takes one of the files for some reason. Any idea why? I took this code from online and the creator wrote that the comment that says this should take all of the csv files.
csvfiles = filenames(endsWith(filenames,'.csv'));
Difficult to say. The code found all my .csv files I had in the folder. Are you sure all your files end with the .csv?
I will keep troubleshooting, but thank you so much for your help.
No problem. I'm glad I could help.
I figured it out. For some reason whether the csv was all caps or lower case mattered.
Good job! Then You can mark this as answered!

Sign in to comment.

More Answers (1)

Cris LaPierre
Cris LaPierre on 16 Sep 2020

1 vote

There are many ways to import a csv file, including
What is best depends on the contents of your files.

Community Treasure Hunt

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

Start Hunting!