4

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?

Eitan T
  • 32,660
  • 14
  • 72
  • 109
user2355358
  • 81
  • 3
  • 7
  • You might find these questions related: [this one](http://stackoverflow.com/questions/14213442/matlab-file-name-with-zero-padded-numbers/14214042#14214042) and [this one](http://stackoverflow.com/questions/15366374/how-can-i-load-100-files-with-similar-names-and-or-string-in-just-one-step-in-ma/15366423#15366423). – Shai Jun 03 '13 at 12:55
  • @Shai Why did you add the [tag:vectorization] tag? I'm not sure how it's related. – Eitan T Jun 03 '13 at 15:05
  • @Shai Please see [my comment](http://stackoverflow.com/questions/16881196/how-to-count-number-of-1-and-0-in-the-matrix?noredirect=1#comment24388824_16881196) for a similar case. Perhaps the solution is vectorized, which is good, but the question was not aimed specifically at vectorization, but rather at simplifying the implementation. – Eitan T Jun 03 '13 at 15:39

1 Answers1

5

use * in dir:

files = dir( fullfile( TopFolder, SubFolder.name, 'PowerOutput*.cvs' ) );
Shai
  • 111,146
  • 38
  • 238
  • 371
  • thanks. Does this also work if there are other .csv files in the same folder, called electric.csv, for example? – user2355358 Jun 03 '13 at 12:36
  • the astrics (`'*'`) replaces any char(s) in the file name. So `'PowerOutput*.cvs'` matches (for example) 'PowerOutput3.cvs', 'PowerOutputWhatWasIThinking.cvs' etc. If you want to find all cvs files in a folder, just `dir('*.cvs')`... – Shai Jun 03 '13 at 12:44