Skip Last Line of .csv File

I'm reading in a .csv file with a large header and one undesired line at the very end of the file. I'm using textscan and the parameter 'headerlines' to successfully skip the header, but I can't figure out how to skip the last line of the file.
I'm having no problems with skipping lines at the beginning of the file, only with skipping the last line. Could anyone offer a detailed description of how to skip the last line of the file?

 Accepted Answer

Jan
Jan on 17 May 2012
You cannot ignore the trailing line using textscan(). I recommend to import all data and delete the last row afterwards. I assume something like this will help:
C = textscan(...);
for iC = 1:length(C)
C{iC} = C{iC}(1:end, :);
end

1 Comment

I removed the last line with a slight change. I used:
C{iC} = C{iC}(1:end-1, :);

Sign in to comment.

More Answers (2)

Walter Roberson
Walter Roberson on 17 May 2012

0 votes

The only way textscan() has to do that is if you provide a count of the number of times you want the format to be applied. This means you would have to know the exact number of lines in the file.
If you do not know the number of lines in the file, then unfortunately MATLAB does not provide any routine that can tell you. You would need to read the file and count the lines.
Kees Pruis
Kees Pruis on 15 Apr 2013

0 votes

A slow but maybe helpfull solution might be the use of fgetl. To be able to use this you need to know what's on the last line which you want to skip. Your code would than be similar to the example below.
while ~feof(fid) && ~strcmp(fgetl(fid),'End of the file') D = textscan(fid); end

Categories

Asked:

on 17 May 2012

Commented:

on 6 Nov 2018

Community Treasure Hunt

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

Start Hunting!