How read in comment style to skip the header of a text file?

조회 수: 12 (최근 30일)
Nazar Adamchuk
Nazar Adamchuk 2021년 6월 17일
편집: Joseph Cheng 2021년 6월 17일
I am trying to read hundreds of .dat file by skipping header lines (I do not know how many of them I need to skip beforehand). Header lines very from 1 to 20 and have at beginning either or "$" oder "!". A sample data (left column - node, right column - microstructure) has always two columns and looks like the following text file in the attachment.
I tried the following codeline, assuming I know beforehand that there 3 lines in header:
fid = fopen('Graphite_Node_Test.txt') ;
data = textscan(fid,'%f %f','HeaderLines',3) ;
fclose(fid);
How can I change the code so that it can read the .dat file without knowing the number of header lines beginning with either "$" or "!" sign?

채택된 답변

Joseph Cheng
Joseph Cheng 2021년 6월 17일
편집: Joseph Cheng 2021년 6월 17일
you can quickly scan the file(s) for the number of header lines like
file= 'Graphite_Node_test.txt';
fid = fopen('Graphite_Node_Test.txt') ;
hlines= 0;
while ~feof(fid)
cline =fgetl(fid); %get the current line
if strcmp(cline(1),'!') | strcmp(cline(1),'$') %check if it starts with ! or $
hlines = hlines+1; %if it does increment headerline counter
else
break %break out once past header
end
end
fseek(fid,0,-1); %rewind file to start
data = textscan(fid,'%f %f','Headerlines',hlines);
fclose(fid);
disp(data)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by