这里有一种更面向对象的方法,使用简单编码的FSM(有限状态机)来控制读取完整数据记录的过程。它比当前发布的其他答案更加冗长,但是它是一种相当灵活和可扩展的方法来处理这些任务,并通过错误检查来完成。在class Record(object):
def __init__(self, time=None, bins=None, fltarr=None):
self.time = time
self.bins = bins
self.fltarr = fltarr
def read(self, file):
""" Read complete record from file into self and return True,
otherwise return False if EOF encountered """
START, STOP, EOF = 0, -1, -99
state = START
while state not in (EOF, STOP):
line = file.readline()
if not line: state = EOF; break
# process line depending on read state
if state == 0:
self.time = float(line)
state = 1
elif state == 1:
self.bins = int(line)
state = 2
elif state in (2, 3):
# ignore line
state += 1
elif state == 4:
self.fltarr = []
last_bin = self.bins-1
for bin in xrange(self.bins):
self.fltarr.append([float(x) for x in line.split()])
if bin == last_bin: break
line = file.readline()
if not line: state = EOF; break
if state != EOF:
state = STOP
return state == STOP
def __str__(self):
result = 'Record(time={}, bins={}, fltarr=[\n'.format(self.time, self.bins)
for floats in self.fltarr:
result += ' {}\n'.format(floats)
return result + '])'
fname = 'sample_data.txt'
with open(fname, 'r') as input:
data = []
while True:
record = Record()
if not record.read(input):
break
else:
data.append(record)
for record in data:
print record
输出:
^{pr2}$