Reading textfile using fopen and textscan
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello,
I've got a textfile 'test_file.txt' which you can find in attachment.
At the bottom of this textfile, you can see ' [Channel Data] '. I would like to extract all headers beneath ' [Channel Data] ' except the last 2. So I would like to extract the headers ' S.No., Data&Time, hf2, hf3, hf4, hf10, hf6, tc18, tc3, tc5, tc7, tc9, tc11, tc12, tc13, tc15, tc16, tc2'. So the 'Alarm in Channels' and the 'Alarm Out' are left out. In total this would give 18 headers. (See picture in attachment for clarification)
I also would like to extract all the data in the rows beneath the headers. These numbers are seperated by a comma (comma delimiter) and in total there are also 18 numbers in 1 row. I am familiar using fopen and textscan, but I'm not sure how to use it to get what I would like to have...
Thank you
댓글 수: 2
채택된 답변
Stephen23
2020년 10월 6일
편집: Stephen23
2020년 10월 6일
This reads your file:
opt = {'Delimiter',',', 'CollectOutput',true};
[fid,msg] = fopen('test_file.txt','rt');
assert(fid>=3,msg)
str = '';
while ~strcmpi(str,'[Channel Data]')
str = strtrim(fgetl(fid));
end
str = fgetl(fid);
hdr = regexp(str,'[^,]+','match');
hdr(strncmpi(hdr,'Alarm',5)) = [];
tmp = repmat({'%f'},1,numel(hdr));
tmp{strcmpi(hdr,'Date&Time')} = '%s'; % or '%{MM/dd/yyyy HH:mm:ss:SSS}D' for datetime
fmt = [tmp{:},'%*[^\n]'];
out = textscan(fid,fmt,opt{:});
fclose(fid);
Giving:
>> out{1}
ans =
1
2
3
4
5
6
>> out{2}
ans =
'04/23/2020 19:42:52:000'
'04/23/2020 19:42:53:000'
'04/23/2020 19:42:54:000'
'04/23/2020 19:42:55:000'
'04/23/2020 19:42:56:000'
'04/23/2020 19:42:57:000'
>> out{3}
ans =
0.0194 0.0292 0.0089 0.0009 0.0119 20.0000 23.0000 22.8000 24.2000 24.3000 25.1000 24.9000 24.3000 24.8000 25.3000 22.4000
0.0194 0.0292 0.0080 0.0006 0.0125 20.0000 23.0000 22.8000 24.2000 24.3000 25.1000 24.9000 24.3000 24.8000 25.3000 22.4000
0.0191 0.0292 0.0071 0.0006 0.0131 20.0000 23.0000 22.7000 24.2000 24.3000 25.1000 25.0000 24.3000 24.8000 25.3000 22.4000
0.0194 0.0292 0.0063 0.0006 0.0137 20.0000 23.0000 22.7000 24.2000 24.3000 25.1000 24.9000 24.3000 24.8000 25.3000 22.4000
0.0197 0.0292 0.0054 0.0003 0.0143 20.0000 23.0000 22.7000 24.2000 24.3000 25.1000 24.9000 24.3000 24.8000 25.3000 22.4000
0.0197 0.0289 0.0048 0.0003 0.0146 20.0000 23.0000 22.8000 24.2000 24.3000 25.1000 24.9000 24.3000 24.8000 25.3000 22.4000
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Import and Export에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!