700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python读取txt文件每一行存为列表 从txt文件中读取一定数量的行 并以python方式转换为list...

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

时间:2018-12-04 07:25:07

相关推荐

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}$

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。