Reputation: 81
How could I check if a number of csv files are present in the current directory?
I have a csv file called PowerOutput.csv, I can see if this exists with
exist('PowerOutput.csv','file')
However, I could have a number of these files e.g. PowerOutput1.csv, PowerOutput2.csv, PowerOutput3.csv and so on.
What is the best way of finding which files exist in a directory?
At the moment I have tried:
TopFolder = pwd;
SubFolder = dir(TopFolder);
SubFolder = {SubFolder.name};
SubFolder(strncmp(SubFolder,'.',1)) = [];
% -- find the number of PowerOutput
num_Power = strncmp({'PowerOutput'}, SubFolder,length('PowerOutput'));
num_Power(num_Power == 0) = [];
num_Power = 1:length(num_Power);
and then I can import the data by:
% -- import inflow
for i = 1:length(num_Power);
filename = fullfile(TopFolder,horzcat('PowerOutput',num2str(num_Power(i)),'.csv'));
fid = fopen(filename);
headers = textscan(fid, '%s%s', 1, 'delimiter',',');
dat = textscan(fid,'%s%f%f','delimiter',',','headerlines',1);
fclose(fid);
end
But this seems like a really long-winded way of doing it. Any suggestions?
Upvotes: 4
Views: 2629
Reputation: 114866
use *
in dir
:
files = dir( fullfile( TopFolder, SubFolder.name, 'PowerOutput*.cvs' ) );
Upvotes: 5