MATLAB: Import CSV file according to timestamp

automatedautomatic;characterscsvimportmonthparametersscanyear

Hello.
I have a bunch of CSV (comma separated value) files that are named randomly based on the MAC ID of the logger that created the file.
What I want to do is write a function that automatically imports the CSV file from the month and year that is defined by the input parameters.
For example:
function [importedvar] = csvMYimport(month, year)
%find out what month and year is wanted and choose the file to import accordingly
The CSV files are all in one folder. The first ten characters of the second line of each CSV file contains a timestamp, for example:
2013-08-01
So the only way I can automate the import is by scanning the first 7 characters of the second row of each CSV file and then choose that file's filename and add it to the path, i.e. "D:\\CSVfiles\CSV932147321.csv"
I have already coded a fitted import process and the error checking to make sure the month and year parameters are put in correctly. [Months: 1, 2, 3, 4,…,12 – years: 2013, 2014, …, etc.]
I just need to find a way to use those inputs (for example Month = 8; Year = 2013) and get Matlab to scan the files, pick out the file name and add it to the string: 'D:\\CSVfiles\'
Is this possible with Matlab?
I would be really greatful for any suggestions!
Marc (P.S. I will be working on another project at the same time, so please don't feel offended if it takes a day or so for me to check the answers)

Best Answer

You could do something like the following (not tested):
function selection = getFilesYearMonth( folder, year, month )
files = dir( fullfile( folder, '*.csv' )) ;
selection = {} ;
for k = 1 : numel( files )
fid = fopen( fullfile(folder, files(k).name), 'r' ) ;
fgetl( fid ) ; % Skip first line.
yearMonth = fscanf( fid, '%f-%f', 2 ) ;
fclose( fid ) ;
if yearMonth(1) == year && yearMonth(2) == month
selection = [selection, files(k).name] ;
end
end
end