fix content .txt file (organize the inside of the .txt file)
7 views (last 30 days)
Show older comments
Hi! How can I transform the file data.txt to data_new.txt?
0 Comments
Answers (2)
dpb
on 16 Jun 2023
Edited: dpb
on 17 Jun 2023
You can try
tYourTable=renamevars(tYourTable,{'Parameters1','Parameters2'},{'Parameters:','Values'});
writetable(tYourTable,'YourTableOutput.txt','Delimiter','\t','WriteVariableNames',1,'QuoteStrings',0)
Given the variable width of the text column data, it's likely the tab spacing won't show up with evenly aligned columns unless you use an application to view it that can set tab spacing wider than the default 8 characters most apps use.
If the above isn't of sufficient beauty, you'll be forced to use low-level i/o with fprintf and fixed-width columns of the needed/desired size.
2 Comments
dpb
on 17 Jun 2023
Edited: dpb
on 17 Jun 2023
Same way; use tab-delimiter it you want a tab-delimited file when you create the first one.
If you want a fixed-width file instead, there's no builtin higher level function in MATLAB to do that; the closest would be compose although it hasn't been expanded to handle tables.
Trying to edit sequential text files in place programmatically is not the way to approach it; write the file as you want it to begin with.
And, reassess the need; what's the point other than pretty? Unless it is to be a formal report or the like, it may well not be worth the effort; if it's only to be an intermediary as input to another code, the code won't care what it looks like.
dpb
on 18 Jun 2023
Edited: dpb
on 18 Jun 2023
As noted before, don't try to fix a malformed text file; create the file correctly in the first place...we'll start from the original to get the data, but unless this is the initial starting point, don't create a comma-delimited file at all, use writetable to output the initial file from the MATLAB table.
OTOH, if the initial file is what was provided by some other process and can't change that process, then
c=readcell('data.txt')
writecell(c,'data1.txt','delimiter','\t')
type data1.txt
0 Comments
See Also
Categories
Find more on Low-Level File I/O 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!