The data file
.... # unknow lines
tag
134
345
256
2345
234
othertag
The matlab solution
%matlab
% to reading the data from the above format file
% if using matlab, it is easy
fid = fopen(filename);
tag1 = 'tag';
while 1
strline = fgetl(fid);
if strcmp('tag',strline) == 1
result = fscanf(fid,'%f',[1,inf]);
fclose(fid);
break;
end
end
The function “fscanf” makes the process very easy.
Today, I want to use python to realize the same function, but a problem was met: how to read the data in one time?
My python solution
The first time
filename = 'test.txt'
startrecord = False
result = []
with open(filename) as f:
for line in f:
line = line.strip()
if line.startswith('tag'):
startrecord = True
continue
if not line:
startrecord = False
if startrecord:
result.append(float(line))
f.close()
print result
[345.0, 2345.0, 234.0]
The new way
Wait for other resolutions