MATLAB Answers

How can I import multiple .csv files that are in separate folders

4 views (last 30 days)
Cole Benson
Cole Benson on 2 Mar 2017
Answered: Image Analyst on 2 Mar 2017
I am trying to import a large set of data and the problem I am running into is that they are stored in multiple folders inside a Main folder. I have changed my directory to this Main folder but it won't let me loop through the .csv files in the Main folder as they each are in their separate folder. Unfortunately, this is how the data is output by our data collection machines so is there a way I can potentially write a code that opens each folder and extracts the file information? I appreciate the help
Edit: I also do not have any sample code as this is the first step in my process

Answers (2)

Meade
Meade on 2 Mar 2017
Try this:
!!Careful, this will find ALL csvs in a folder!! You can further narrow down, e.g. by filename, using additional logical indices
mainFolder = uigetdir(); % Selectyour Main folder
[~,message,~] = fileattrib([mainFolder,'\*']);
fprintf('\n There are %i total files & folders.\n',numel(message));
allExts = cellfun(@(s) s(end-2:end), {message.Name},'uni',0); % Get exts
CSVidx = ismember(allExts,'csv'); % Search ext for "CSV" at the end
CSV_filepaths = {message(CSVidx).Name}; % Use CSVidx to list all paths.
fprintf('There are %i files with *.CSV exts.\n',numel(CSV_filepaths));
for ii = 1:numel(CSV_filepaths)
% Do import here
end

Community Treasure Hunt

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

Start Hunting!

Translated by