How can I write data to a text file in a user-specified location that is already populated with a standard header?
4 views (last 30 days)
Show older comments
Currently, I am working on an app that can successfully write 4 columns of data to a text file in a user-defined file location, at the push of a button. I am accomplishing this task using the following code:
% Button pushed function: ExporttotxtButton
function ExporttotxtButtonPushed(app, event)
[fn,pn] = uiputfile('.rdf','RoadProfile_bumpy_fl.rdf','RoadProfile_bumpy_fl.rdf');
if isnumeric(fn) % user canceled
return % return early
end
% write the table to the user-specified file
writematrix(app.UITable.Data,fullfile(pn,fn),'Delimiter','tab','FileType','text');
However, I have a very long string of text (about 47 lines of text...not included here to save space) that I would like to include as a header in the generated text file. The goal is to have the end result be a text file that already has the header populated with a standard 47 lines of text, and then write the matrix data below the header as I am already doing. I have tried using the following:
fprintf(fullfile(pn,fn),'%s\n',['long_string_of_text..' ...
'creating new line each time\n'...]
But, this doesn't seem to work. Any help would be much appreciated. I can post the full text that I want to include in the header if that is necessary. Thank you.
0 Comments
Accepted Answer
Voss
on 11 Sep 2024
You can call writematrix with 'WriteMode','append' to write the data to a text file that already contains the header.
So the complete file would be built by doing something like:
header = ["some";"lines";"of";"text";"in";"some";"form";"or";"other"];
file_name = fullfile(pn,fn);
% write the header
writematrix(header,file_name,'FileType','text');
% write the data
writematrix(app.UITable.Data,file_name,'Delimiter','tab','FileType','text','WriteMode','append');
Or use writecell or writetable to write the header, depending on its data type, then writematrix(_,'WriteMode','append') the data as above.
More Answers (1)
Les Beckham
on 11 Sep 2024
Edited: Les Beckham
on 11 Sep 2024
Probably the easiest way to do this is to create a text file containing your header text and then call system() to concatenate that file with the one that you have written your data table to.
For example (on Windows):
% insert after your writematrix() call above:
cmd = sprintf('copy HeaderText.txt + %s %s', fullfile(pn,fn), fullfile(pn,fn))
system(cmd)
Or on Linux:
% insert after your writematrix() call above:
cmd = sprintf('cat HeaderText.txt %s > %s', fullfile(pn,fn), fullfile(pn,fn))
system(cmd)
Note that I haven't tested either of these examples, but they should get you started.
0 Comments
See Also
Categories
Find more on Text Data Preparation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!