Stop writing blank line at the end of CSV file (using MATLAB)

Posted by Grant M. on Stack Overflow See other posts from Stack Overflow or by Grant M.
Published on 2010-05-18T15:06:25Z Indexed on 2010/05/18 20:50 UTC
Read the original article Hit count: 171

Filed under:
|

Hello all ...

I'm using MATLAB to open a batch of CSV files containing column headers and data (using the 'importdata' function), then I manipulate the data a bit and write the headers and data to new CSV files using the 'dlmwrite' function. I'm using the '-append' and 'newline' attributes of 'dlmwrite' to add each line of text/data on a new line.

Each of my new CSV files has a blank line at the end, whereas this blank line was not there before when I read in the data ... and I'm not using 'newline' on my final call of 'dlmwrite'.

Does anyone know how I can keep from writing this blank line to the end of my CSV files?

Thanks for your help,

Grant

EDITED 5/18/10 1:35PM CST - Added information about code and text file per request ... you'll notice after performing the procedure below that there appears to be a carriage return at the end of the last line in the new text file.

Consider a text file named 'textfile.txt' that looks like this:

Column1, Column2, Column3, Column4, Column 5

1, 2, 3, 4, 5

1, 2, 3, 4, 5

1, 2, 3, 4, 5

1, 2, 3, 4, 5

1, 2, 3, 4, 5

Here's a sample of the code I am using:

% import data

importedData = importdata('textfile.txt');


% manipulate data

importedData.data(:,1) = 100;


% store column headers into single comma-delimited
% character array (for easy writing later)

columnHeaders = importedData.textdata{1};

for counter = 2:size(importedData.textdata,2)

    columnHeaders = horzcat(columnHeaders,',',importedData.textdata{counter});

end


% write column headers to new file

dlmwrite('textfile_updated.txt',columnHeaders,'Delimiter','','newline','pc')


% append all but last line of data to new file

for dataCounter = 1:(size(importedData.data,2)-1)

    dlmwrite('textfile_updated.txt',importedData.data(dataCounter,:),'Delimiter',',','newline','pc','-append')

end


% append last line of data to new file, not
% creating new line at end

dlmwrite('textfile_updated.txt',importedData.data(end,:),'Delimiter',',','-append')

© Stack Overflow or respective owner

Related posts about matlab

Related posts about csv