Thread Subject: how to append a column to a existing txt file?

Subject: how to append a column to a existing txt file?

From: Arthur Zheng

Date: 6 Jul, 2009 15:07:01

Message: 1 of 2

fid = fopen('temp.txt', 'wt');
fprintf(fid, '%s\t%s\r\n', 'property1', 'property2');
for i = 1:3
     fprintf( fid, '%s\t%s\r\n', ['value1_' , num2str(i)], ['value2_' , num2str(i)] );
end
fclose(fid);

The file temp.txt would then look like:
property1 property2
value1_1 value2_1
value1_2 value2_2
value1_3 value2_3

Now I want to add a column with property name 'prop3' and with whatever value 'value3' to temp.txt. How can I append that column? Note I don't want to rewrite the existing two columns. I want to append one column so that the temp.txt would look like
property1 property2 property3
value1_1 value2_1 value3_1
value1_2 value2_2 value3_2
value1_3 value2_3 value3_3

The reason I don't want to rewrite the existing two columns is that the actually temp.txt file I am dealing with is very large, and it takes a lot of time to rewrite the existing columns. thanks.

Subject: how to append a column to a existing txt file?

From: Dan Pearce

Date: 6 Jul, 2009 17:07:01

Message: 2 of 2

Pretty sure you can't just add a column without rewriting it. Such files are plain text and don't contain any kind of information that would allow you to specify where a column would be added.

Rewriting the file is probably your only option. This would work and I can't see it taking that long, even for a very large file.

inputfilename = 'temp.txt'
outputfilename = 'output.txt'

fid1 = fopen(inputfilename, 'rt')
fid2 = fopen(outputfilename, 'wt')

while feof(fid1) == 0
   tline = fgetl(fid1)
   
    nline = [tline, ' New Column data', '\n']
    fprintf(fid2, nline);
end
fclose(fid1)
fclose(fid2)

At risk of starting a flame war, MATLAB might not be the best language for the job though. If you are simply hammering large text files, C/C++/Perl could be quicker...

Tags for this Thread

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Tag Activity for This Thread
Tag Applied By Date/Time
fprintf Arthur Zheng 6 Jul, 2009 11:09:02
rssFeed for this Thread

Contact us at files@mathworks.com