Adding a header to a .txt file
83 次查看(过去 30 天)
显示 更早的评论
I have a code right now where I ask the user to select the text file that has 3 columns of data. I am currently adding a timestamp and exporting the text file back out to the user... what I could use help on is adding a header to the top of the data. I don't know what commands to write in my code in order to do this. Any suggestions at all would be greatly appreciated!!
0 个评论
回答(2 个)
Jürgen
2012-8-13
编辑:Walter Roberson
2012-8-13
I am not 100% sure what you are trying to do but if you want to write to a text file, that is quite well explained in the help of Matlab with an example, see below,
if first you read your data ( 3 columns) to a matlab matrix then open a new text file, write the header with fprintf then add the data, also with fprintf ( see example below) finally close the file,
probably you can also first open the orginal txtfile and add the header before the data, but I do not know the command by heart, I know you can append txt using fprintf with "a"
hope this helps a bit
regards,J
% create a matrix y, with two rows
x = 0:0.1:1;
y = [x; exp(x)];
% open a file for writing
fid = fopen('exptable.txt', 'w');
% print a title, followed by a blank line
fprintf(fid, 'Exponential Function\n\n');
% print values in column order
% two values appear on each row of the file
fprintf(fid, '%f %f\n', y);
fclose(fid);
0 个评论
Walter Roberson
2012-8-13
There is no mechanism to insert into a file, only mechanisms to overwrite within a file and mechanisms to create new files.
Jürgen's suggestion of reading the data in, creating a new file, writing the header, and then writing the data, is a workable solution (provided the file fits into memory.) It could be followed by renaming the new file to the old name.
Also workable:
fidin = fopen('InputFile.txt', 'rt');
fidout = fopen('OutputFile.txt', 'wt');
fprintf(fidout, '%s\n', 'The Header Goes Here');
while true
thisline = fgets(fidin);
if ~ischar(thisline); break; end %end of file
fwrite(fidout, thisline);
end
fclose(fidout);
fclose(fidin);
And then rename the new file to the old one.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!