How to pass multiple comment style to skip the header of a text file?
14 次查看(过去 30 天)
显示 更早的评论
Hi I am pretty new to Matlab, so I need some help. I am trying to read a .txt file by skipping first couple lines (I do not know how many of them I need to skip beforehand). A sample data looks like the following:
<NUMBER OF ZONES 2
<NUMBER OF NODES> 4
<FIRST THRU NODE> 1
<NUMBER OF LINKS> 5
<END OF METADATA>
~ Init node Term node Capacity Length Free Flow Time BPower Speed limit Toll Type;
1 3 1 100 0.00000001 1000000000 1 0 0 1;
1 4 1 100 50 0.02 1 0 0 1;
3 2 1 100 50 0.02 1 0 0 1;
3 4 1 100 10 0.1 1 0 0 1;
4 2 1 100 0.00000001 1000000000 1 0 0 1;
So here, I would like to skip the lines starting with either < or ~. I am using the following codeline:
C = textscan(fid2, '%s' , 'Delimiter', ';', 'CommentStyle' , '<');
And I can skip the first 5 lines. However, I cannot skip the 6th one. I tried to pass multiple commentstyle but it gave an unknown error.
If someone can help me to not read the lines with ~ or <, I'd be glad.
PS: the sample file is easy to see, however, for other files I might not know where exactly the lines that I have to skip are.
Thanks in advance.
0 个评论
采纳的回答
Guillaume
2015-2-26
I don't think textscan supports multiple comment style so you'll have to go a bit more low level:
fid = fopen('somefile', 'rt');
filepos = 0;
tline = fgetl(fid);
%read lines until end of file is reached (tline empty) or not a comment
while ~isempty(tline) & any(strncmp(tline, {'<', '~'}))
filepos = ftell(fid);
tline = fgetl(fid);
end
%the last line read was not a comment, rewind to its beginning
fseek(fid, filepos, 'bof');
%now use textscan, comments are already skipped
C = textscan(fid2, '%s' , 'Delimiter', ';', ');
fclose(fid);
1 个评论
Nazar Adamchuk
2021-6-17
编辑:Nazar Adamchuk
2021-6-17
Hi this script ist not right. Why ist was markes as "accepted?
For expample, line five has tio have && and not &. In the same line: what sort of the command "strncmp" is?
"fid2 in the 10th line ist not defined!
Can you redo your solution?
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Large Files and Big Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!