python读取txt文件每一行存为列表,从txt文件中读取一定数量的行,并以python方式转换为list...

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-31 01:49   11   0

这里有一种更面向对象的方法,使用简单编码的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}$

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP