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

该博客介绍了一种面向对象的方法,通过实现一个有限状态机(FSM)来读取和处理数据记录。这个FSM在Python中定义,能够优雅地处理文件中的数据,并在遇到文件结束(EOF)时停止。记录类包含读取、初始化和字符串表示方法,确保数据正确解析和打印。示例代码展示了一个如何从文件中读取并存储时间、bin数量和浮点数数组的记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值