I have a txt file containing a Matrix separated by commas. I would like to add a comma after the last column on every row.

4 次查看(过去 30 天)
I have a .txt file containing >200'000 rows and 12 columns separated by commas (only numbers, no characters). I would like to add a comma after the last column on every row without adding any values in a 13. column. (example below).
example of what I have:
1,2,3,4,5,6,7,8,9,10,11,12
1,2,3,4,5,6,7,8,9,10,11,12
example of what I am trying to get:
1,2,3,4,5,6,7,8,9,10,11,12,
1,2,3,4,5,6,7,8,9,10,11,12,
Thank you already for your time.

采纳的回答

dpb
dpb 2022-4-28
编辑:dpb 2022-4-30
data=readlines('yourfile.txt'); % read file as string array
data=data(strlength(data)>0); % save only non-empty lines
data=strcat(data,","); % catenate "," on end
writematrix(data,'yournewfile.txt','QuoteStrings',0) % write back out, don't quote
  4 个评论
dpb
dpb 2022-4-28
编辑:dpb 2022-4-30
I did just check -- it is, indeed, whether or not there is that last newline or not.
The above fix will remove it if is there in the original; leaving it out will produce the extra ','; a little extra logic could have both by testing if there is a blank line and only appending the ',' to those lines that are longer.
data=readlines('yourfile.txt'); % read file as string array
ix=strlength(data)>0; % find non-empty lines
data(ix)=strcat(data(ix),","); % catenate "," on end
writematrix(data,'yournewfile.txt','QuoteStrings',0) % write back out, don't quote

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by