extracting data from a text file to a spreadsheet

Hello,
I have *.txt files in different folders as shown below;
Main Dir\Sub A\a1.txt, a2.txt, a3.txt......
Main Dir\Sub B\b1.txt, b2.txt, b3.txt......
Main Dir\Sub C\c1.txt, c2.txt, c3.txt......
Each txt file has the same format and has sevaral parameters. Below are just a few...
param: 600
SN number: 2010
Sim method: Low
I need to get these data to an excel spreasheet in below format;
param SN number Sim method
a1 600 2010 Low
a2 700 2011 High
a3 800 2012 Medium
b1 900 2013 High
b2 1000 2014 Low
b3 1100 2015 Low
Appreciate your assistance.
Thanks

 채택된 답변

Walter Roberson
Walter Roberson 2020년 7월 23일
dinfo = dir('Main Dir\*\*.txt');
filenames = fullfile({dinfo.folder}, {dinfo.name});
numfiles = length(filenames);
data = cell(numfiles, 4);
for K = 1 : numfiles
thisfile = filenames{K};
[~, basename, ~] = fileparts(thisfile);
fid = fopen(thisfile);
datacell = textscan(fid, 'param: %f\nSN number: %f\nSim method: %s',1);
fclose(fid);
data{K,1} = basename;
data{K,2} = datacell{1};
data{K,3} = datacell{2};
data{K,4} = datacell{3}{1};
end
datatable = cell2table(data, 'VariableNames', {'file', 'param', 'SN number', 'Sim method'});
writetable(datatable, 'OutputFilename.xslx');

댓글 수: 3

Binu
Binu 2020년 7월 23일
Hi Walter,
Thanks for the reply, seems like it works, but at the very end I got this error message;
"Error using writetable (line 121)
Unrecognized file extension '.xslx'. Use the 'FileType' parameter to specify the file type."
"Error in Untitled5 (line 18)
writetable(datatable, 'OutputFilename.xslx');"
Hope you can help
Many thanks
Binu
Binu 2020년 7월 23일
Sorry, I got it. there is a typo in the extension.
It worked, but the columns in the excel file are empty.
Binu
Binu 2020년 7월 23일
The 'param' column is filled but the other two columns are still :(

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

질문:

2020년 7월 23일

댓글:

2020년 7월 23일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by