fix content .txt file (organize the inside of the .txt file)

6 次查看(过去 30 天)
Hi! How can I transform the file data.txt to data_new.txt?

回答(2 个)

dpb
dpb 2023-6-16
编辑:dpb 2023-6-17
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 个评论
dpb
dpb 2023-6-17
编辑:dpb 2023-6-17
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
dpb 2023-6-18
编辑:dpb 2023-6-18
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')
c = 2×3 cell array
{'data 1'} {'data 2'} {'data 3'} {[ 50]} {[ 140]} {[ 36]}
writecell(c,'data1.txt','delimiter','\t')
type data1.txt
data 1 data 2 data 3 50 140 36

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by