how to count the number of lines of an external txt file

96 Ansichten (letzte 30 Tage)
Hugo
Hugo am 2 Mai 2022
Kommentiert: Rik am 2 Mai 2022
Hi,
I would like to know how I can count the number of lines (not empty) of an external text file, let's say, a.txt, and save it in a variable.
Best regards,

Antworten (2)

Davide Masiello
Davide Masiello am 2 Mai 2022
Not sure if there is a better way, but this will work
fid = fopen('a.txt','r');
n = 0;
while ~feof(fid)
fgetl(fid);
n = n+1;
end
fclose(fid);
n
n = 15
  1 Kommentar
Rik
Rik am 2 Mai 2022
Your code doesn't skip empty lines in the middle of the file
% Write an example file with a blank line
fid=fopen('a.txt','w');
fprintf(fid,'line1\n\nline3\n');
fclose(fid);
% Run your code
fid = fopen('a.txt','r');
n = 0;
while ~feof(fid)
fgetl(fid);
n = n+1;
end
fclose(fid);
n
n = 3

Melden Sie sich an, um zu kommentieren.


Rik
Rik am 2 Mai 2022
The problem with your question is that it lacks a definition of line. If your file ends with char(10) or char(13) does that signify a new line (meaning you have a trailing empty line)?
txt=readfile('https://www.mathworks.com/matlabcentral/answers/uploaded_files/985140/a.txt',...
'EmptyLineRule','skip')
txt = 15×1 cell array
{'asd'} {'er' } {'234'} {'sdf'} {'dfh'} {'fy' } {'578'} {'fg' } {'dfg'} {'w34'} {'dfg'} {'df' } {'fh' } {'yu' } {'19' }
a=numel(txt)
a = 15
This is the choice that my readfile function makes. If you use R2020b or later you will be able to use the builtin readlines function. For older releases (or GNU Octave) you will need to use readfile.

Kategorien

Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by