How can I write data to a text file in a user-specified location that is already populated with a standard header?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2024-9-11
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.
更多回答(1 个)
Les Beckham
2024-9-11
编辑:Les Beckham
2024-9-11
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Data Preparation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!