Writing new column in Text file

25 ビュー (過去 30 日間)
Muhammad
Muhammad 2014 年 1 月 27 日
編集済み: kjetil87 2014 年 1 月 28 日
I have 31 column in text file. I am trying to write new (32nd) column in existing text file. By using append the new column is placed at the end of text file. Any suggestions to write new column please...
  2 件のコメント
José-Luis
José-Luis 2014 年 1 月 27 日
編集済み: José-Luis 2014 年 1 月 27 日
You need to import the whole file, append the data at the end of each line and then save it. Appending to the file is not going to do the trick.
Muhammad
Muhammad 2014 年 1 月 27 日
Appreciated. How can I append the data at the end of each line? May be by for loop it is possible. Let consider I have a text file with 3x3 matrix; 7 3 3 2 3 4 5 4 2
and I would like to add a fourth column; 4 5 1 What do you suggest ?

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

回答 (1 件)

kjetil87
kjetil87 2014 年 1 月 27 日
As far as i know, there is no possability of writing in the middle of a file and have the rest of the data just shift along (correct me if im wrong).
So i guess your best choice here would be to read to old file into memory, append your new data to every line (so it will be a new column) and then overwrite the old file.
  3 件のコメント
kjetil87
kjetil87 2014 年 1 月 28 日
編集済み: kjetil87 2014 年 1 月 28 日
Hmmm, i guess fgetl would be usefull here.
fid=fopen('original.txt');
fidNew=fopen('newTxt.txt','w+');
newCol ='451';
cntr=1;
while(true)
line = fgetl(fid); %fgetl does not return the /n character
if line==-1 %line==-1 indicates end of file.
break;
end
fprintf(fidNew,line);
fprintf(fidNew,[' ',newCol(cntr),'\n'] );
cntr=cntr+1;
end
fclose(fid);
fclose(fidNew);
To do this without creating a new file, you must store line + the additional characters in e.g a cell matrix. Then close the old file, re open it using the 'w+' command and do another loop to write out the cell.
There might be alot of other ways to do this but atleast this way you can easily see what is actually being done.
Hope this gets you on your way towards what you need =)
kjetil87
kjetil87 2014 年 1 月 28 日
編集済み: kjetil87 2014 年 1 月 28 日
On second thoughst, if you know that there is allways a matrix in the text file you can just use
contents = load('original.txt');
contents(:,end+1)=[4,5,1];
fid=fopen('original.txt','w+');
fprintf(fid,'%d %d %d %d\n',tt);
fclose(fid);

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

カテゴリ

Help Center および File ExchangeData Import and Export についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by