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}$
總結
以上是生活随笔為你收集整理的python读取txt文件每一行存为列表,从txt文件中读取一定数量的行,并以python方式转换为list...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php怎么引入外部css文件,js如何引
- 下一篇: Js获取字符串的显示宽度/高度