writetable without trailing empty line

18 ビュー (過去 30 日間)
Luke Hicks
Luke Hicks 2019 年 4 月 3 日
コメント済み: Luke Hicks 2024 年 11 月 23 日 16:14
I am trying to print a cell array to a .txt file and the formatting needs to be perfect in order to import properly into another program.
I am using r2018b which does not support writecell or using fprintf with a cell array.
My current approach is converting the cell array into a table and then using writetable to export it to a .txt file. The problem is that the .txt file has a trailing new line at the end of the document that I don't want. Is there a way to export this data without the trailing new line?
Thank you!
  1 件のコメント
Stakis93
Stakis93 2020 年 9 月 28 日
Hi,
Have you found any solution to this issue ?
I'd like to export my table (using writetable) with the exact number of rows as well, and without the last extra empty row.
Thank you !

サインインしてコメントする。

採用された回答

Aditya
Aditya 2024 年 11 月 21 日 5:07
This is a legacy behavior that writetable has adopted from POSIX standards. Here's a post on why text files end with a newline:
A workaround would be by using low-level file IO functions. Here's a sample example on how to acheive it:
filename = 'SampleFile.txt';
cellArray = {'Name', 'Age'; 'Alice', 30; 'mark', 43,};
% Convert cell array to table
T = cell2table(cellArray(2:end,:), 'VariableNames', cellArray(1,:));
writetable(T,filename,'FileType','text','Delimiter','\t');
fid = fopen(filename, "r");
fidNew = fopen("UpdatedFile.txt", "w");
fseek(fid, -2, "eof");
pos = ftell(fid);
frewind(fid);
A = fread(fid, pos);
fwrite(fidNew, A);
fclose(fid);
fclose(fidNew);
Hope this helps!
  1 件のコメント
Luke Hicks
Luke Hicks 2024 年 11 月 23 日 16:14
I haven't tested the answer, but looking over the code it seems like this would fit the need. Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by