MATLAB: How to write names of many files in single excel file along with its folder name

filefindMATLABtext filexlsreadxlswrite

Dear experiences
i have many folders where every folder contain large number of text files.. i need to write their names along with parent directory name in an excel file.. such as following:
for example if there are master folder include 100 folders { fol1, fol2, fol3..etc} in every sub-folder{fol1,fol2..etc} there are some text files .. i need to write their names in an excel file where first column contain sub-folder name, and second columns contain the names of text files in that sub-folder name, and so on for others .. all result in a single excel file.. such that.
A column B column
fol1 1st text file name in fol1
fol1 2nd text file name in fol1
fol2 1st text file name in fol2
etc..
i have tested the following code but its write all files in first row..
projectdir = 'D:\masterfiles';
xls_filename ='D:\masterfiles\master.xls'
column_range = A;
row_range = 2;
xls_sheet = 'Sheet1';
dinfo = dir(projectdir);
dinfo(~[dinfo.isdir]) = []; %remove non-folders
dinfo(ismember({dinfo.name}, {'.', '..'})) = []; %remove . and .. directories
num_subdir = length(dinfo);
for S = 1 : num_subdir
this_subdir = dinfo(S).name;
subdinfo = dir( fullfile(projectdir, this_subdir, '*.htm*') );
num_subfile = length(subdinfo);
for F = 1 : num_subfile
this_file = subdinfo(F).name;
xlswrite(xls_filename,{dinfo(S).name}, xls_sheet, 'A');
xlswrite(xls_filename,{this_file}, xls_sheet, xlscol(row_range));
row_range =row_range + 1;
end
end
thanks for any suggestion.

Best Answer

Assuming you're using R2016b, where dir supports recursing into folder these 4 lines are all you need:
projectdir = 'D:\masterfiles';
t = struct2table(dir(fullfile(projectdir, '*\*.txt'))); %find text files in all immediate subdirectories of projectdir
t.folder = strrep(t.folder, fullfile(projectdir, '\'), ''); %fullfile(path, '\') canonise the path
writetable(t(:, {'folder', 'name'}), fullfile(projectdir, 'master.xls');