Hi, I want to read text files from sub-sub folders: Architecture: Mainfolder Tool1 sub-subFolder1 sub-subFolder2 ..... ..... Tool2 sub-subFolder1 sub-subFolder2 ..... ..... ......1. Read text files by each sub-folder(i.e, Tool1, Tool2, etc)2. Output Tool1.xlsx, Tool2.xlsx
I use the following code, but I can access sub-sub folders.
% - Define output header.
header = {'RainFallID', 'IINT', 'Rain Result', 'Start Time', 'Param1.pipe', ... '10 Un Para2.pipe', 'Verti 2 mixing.dis', 'Rate.alarm times'} ;Mainfolder='Mainfolder';outLocatorFolder='OutputFolder'; nHeaderCols = numel( header ) ; % - Build listing sub-folders of main folder.
% D_main = dir( 'D:\Mekala_Backupdata\Matlab2010\Mainfolder' ) ;
D_main = dir(Mainfolder ) ; D_main = D_main(3:end) ; % Eliminate "." and ".."
% - Iterate through sub-folders and process.
for dId = 1 : numel( D_main ) % - Build listing files of sub-folder.
D_sub = dir( fullfile(Mainfolder, D_main(dId).name, '*.txt' )) ; nFiles = numel( D_sub ) ; keyboard % - Prealloc output cell array.
data = cell( nFiles, nHeaderCols ) ; % - Iterate through files and process.
for fId = 1 : nFiles % - Read input text file.
inLocator = fullfile(Mainfolder, D_main(dId).name, D_sub(fId).name ) ; content = fileread( inLocator ) ; % - Extract relevant data.
rainfallId = str2double( regexp( content, '(?<=RainFallID\s+:\s*)\d+', 'match', 'once' )) ; iint = regexp( content, '(?<=IINT\s+:\s*)\S+', 'match', 'once' ) ; rainResult = regexp( content, '(?<=Rain Result\s+:\s*)\S+', 'match', 'once' ) ; startTime = strtrim( regexp( content, '(?<=Start Time\s+:\s*).*?(?= -)', 'match', 'once' )) ; param1Pipe = str2double( regexp( content, '(?<=Param1.pipe\s+[\d\.]+\s+\w+\s+)[\d\.]+', 'match', 'once' )) ; tenUn = str2double( regexp( content, '(?<=10 Un Para2.pipe\s+[\d\.]+\s+\w+\s+)[\d\.]+', 'match', 'once' )) ; verti2 = regexp( content, '(?<=Verti 2 mixing.dis\s+\S+\s%\s+)\S+', 'match', 'once' ) ; rateAlarm = strtrim( regexp( content, '(?<=Rate.alarm times\s+\S+\s+)[^\r\n]+', 'match', 'once' )) ; % - Populate data cell array.
data(fId,:) = {rainfallId, iint, rainResult, startTime, ... param1Pipe, tenUn, verti2, rateAlarm} ; end % - Output to XLSX.
% outLocator = fullfile( 'D:\Mekala_Backupdata\Matlab2010\OutputFolder', sprintf( '%s.xlsx', D_main(dId).name )) ;
outLocator = fullfile(outLocatorFolder, sprintf( '%s.xlsx', D_main(dId).name )) ; fprintf( 'Output XLSX: %s ..\n', outLocator ) ; xlswrite( outLocator, [header; data] ) ; end
many thanks in advance,
Best Answer