Import and modify " .txt" files
이전 댓글 표시
Hi
I have some ".txt" files with this structure :
useless
useless
useless
...
data
data
...
useless
useless
useless
data
...
And I would like to have a .txt file like this :
data
data
data
...
I just know that each first line of data section begins with '1' but the length of the headerline (useless) is not fixed ! So I would like to iterate until lines begins with '1' and then keep the data.
How would you do that the easiest way ?
Thanks a lot
댓글 수: 5
Walter Roberson
2015년 11월 26일
How can you tell when you have reached the end of a block of data?
What is the format of each line of the data section? Is it a single numeric value per line?
johnmay
2015년 11월 26일
Thorsten
2015년 11월 26일
It would be best if you provide a sample file.
johnmay
2015년 11월 26일
johnmay
2015년 11월 26일
답변 (2개)
Thorsten
2015년 11월 26일
Copy those lines that have four numbers:
fid = fopen('file.txt', 'r');
fid2 = fopen('file2.txt', 'w');
line = fgets(fid);
while line ~= -1
[~, count] = sscanf(line, '%f');
if count == 4
fprintf(fid2, '%s', line);
end
line = fgets(fid);
end
fclose(fid)
fclose(fid2)
댓글 수: 6
johnmay
2015년 11월 26일
johnmay
2015년 11월 26일
편집: Walter Roberson
2022년 7월 31일
Thorsten
2015년 11월 26일
That's weird. It works smoothly for me. You could add a
disp(line)
disp(count)
pause
in the loop and see if the lines are properly detected.
johnmay
2015년 11월 26일
Thorsten
2015년 11월 26일
You mean reading and write to the same file? No, I don't think so.
johnmay
2015년 11월 26일
johnmay
2015년 11월 26일
0 개 추천
댓글 수: 2
Walter Roberson
2015년 11월 27일
Before the loop:
n = 2; %whatever is appropriate
fmt = repmat('%f ', 1, n);
fmt(end:end+1) = '\n'; %newline, unrelated to the variable 'n'
In the loop:
[data, count] = sscanf(line, '%f');
if count >= n
fprintf(fid2, fmt, data(1:n));
end
johnmay
2015년 12월 1일
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!