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

这里有一种更面向对象的方法,使用简单编码的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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值