从.txt文件中读取数据表并将其解析为变量

时间:2018-06-04 02:02:06

标签: python python-2.7

我需要用python 2.7从.txt文件中读取数据表,并将其解析为变量先生... 我希望有人帮助我..

我有关于.txt(10项)的数据:

LEW01,14/01/2016,07:50:00,15.6,-19,943,-8.7,-228,-19,943,-8.7,-0.9,48.5,4.14,12.39
LEW01,14/01/2016,08:00:00,16.2,-18,944,-8.6,-229,-19,943,-8.6,-0.9,48.5,4.14,12.39
LEW01,14/01/2016,08:10:00,16.8,-19,943,-8.7,-228,-18,944,-8.6,-0.9,48.4,4.16,12.39
LEW01,14/01/2016,08:20:00,17.6,-18,944,-8.6,-229,-18,943,-8.6,-0.9,48.5,4.16,12.44
LEW01,14/01/2016,08:30:00,18.4,-19,943,-8.6,-229,-18,943,-8.6,-0.9,48.5,0.96,12.44
LEW01,14/01/2016,08:40:00,19.4,-18,944,-8.6,-230,-18,943,-8.6,-0.9,48.4,4.18,12.49
LEW01,14/01/2016,08:50:00,20.8,-19,943,-8.7,-230,-18,943,-8.6,-0.9,48.6,4.18,12.49
LEW01,14/01/2016,09:00:00,22.2,-18,944,-8.6,-231,-18,942,-8.6,-0.9,48.6,4.18,12.49
LEW01,14/01/2016,09:10:00,23.4,-19,943,-8.7,-232,-17,942,-8.6,-0.9,48.6,4.18,12.54
LEW01,14/01/2016,09:20:00,24.6,-18,944,-8.6,-233,-17,942,-8.6,-0.9,48.7,4.18,12.59

当我用代码python编译时:

with open('data_peng.txt') as x:
    for rec in x:
        a=rec.split(',')[0]
        b=rec.split(',')[1]
        c=rec.split(',')[2]
        d=rec.split(',')[3]
        e=rec.split(',')[4]
        f=rec.split(',')[5]
        g=rec.split(',')[6]
        h=rec.split(',')[7]
        i=rec.split(',')[8]
        j=rec.split(',')[9]
        k=rec.split(',')[10]
        l=rec.split(',')[11]
        m=rec.split(',')[12]
        n=rec.split(',')[13]
        o=rec.split(',')[14]

输出:

>>> a
'LEW01'
>>> b
'14/01/2016'
>>> c
'09:20:00'
>>> d
'24.6'
>>> e
'-18'
>>> f
'944'
>>> g
'-8.6'
>>> h
'-233'
>>> i
'-17'
>>> j
'942'
>>> k
'-8.6'
>>> l
'-0.9'
>>> m
'48.7'
>>> n
'4.18'
>>> o
'12.59'

我想要的,例如变量c:

>>> c
 [07:50:00,08:00:00,08:10:00,08:20:00,08:30:00,08:40:00,08:50:00,09:00:00,09:10:00,09:20:00]

请帮助我,非常感谢

2 个答案:

答案 0 :(得分:1)

这是一个快速解决方案,它将使用您要查找的列名填充单个对象:

import csv

o = {}
cols = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o']
with open('data_peng.txt', 'r') as csvin:
   csvin = csv.reader(csvin)
   for row in csvin:
       for idx, col in enumerate(cols):
           o.setdefault(col, []).append(row[idx])

print o['c']

答案 1 :(得分:0)

怎么样:

with open('data_peng.txt') as x:
    col3 = [line.split(',')[2] for line in x]

print(col3)

话虽如此,它看起来像一个CSV,任何更复杂的解析都可能受益于python的内置csv module的使用。

另外,我编辑了你问题的格式,请确保我没有改变任何重要的内容。