Import files in a folder containing certain extension

11 views (last 30 days)
Hello, I have many csv files. I am looking to write a couple lines to import specific ones.
There are 0-39 files for each time step (1-5). For example, the format 'pp0.1.csv' indicates file 0/39 for time step 1. I want to import all of the files containing the end '.5.csv' into matlab. Thus pp0-pp39, with that extension. They are all in the same folder. Thanks.

Answers (1)

Stephen23
Stephen23 on 28 Feb 2018
Edited: Stephen23 on 26 Apr 2021
P = 'absolute/relative path to where the files are saved';
S = dir(fullfile(P,'*.5.csv'));
S = natsortfiles(S); % optional, see below.
for k = 1:numel(S)
F = fullfile(P,S(k).name);
S(k).data = csvread(F);
end
If you want the files loaded in numeric order then download my FEX submission natsortfiles:
  7 Comments
Geena Elghossain
Geena Elghossain on 2 Mar 2018
If it would make things simpler- I actually only want the data from the 13, 15 and 16th columns from all 40 of the files. That's the "Result" , " Points 1" and "Points 2" columns respectively.
Stephen23
Stephen23 on 2 Mar 2018
"When I run the initial code, I still get a bunch of errors."
This is the first time that you have mentioned that you are getting an error message. It seems that the file you are trying to read cannot be read by csvread, probably because the file uses double quotes around numeric values (whereas csvread requires numeric values to be without quotes). You could probably use textscan or readtable instead. If you want help with this then please make a new comment, and upload a sample file by clicking on the paperclip button.

Sign in to comment.

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!