首页 > 解决方案 > 用python查找第一行数据

问题描述

我有一个看起来像这样的数据文件,文件类型是一个列表。

############################################################
# Tool
# File: test
#
# mass: mass in GeV
# spectrum: from 1 to 100 GeV
###########################################################
# mass (GeV)   spectrum (1-100 GeV)
10  0.2822771608053263
20  0.8697454394829301
30  1.430461657476815
40  1.9349004472432392
50  2.3876849629827412
60  2.796620869276766
70  3.1726347734996727
80  3.5235401505002244
90  3.8513847250834106
100 4.157478780924807

为了读取数据,我通常必须计算第一组数字之前的行数,然后 for 循环遍历文件。在这个文件中它的 8 行

spectrum=[]
mass=[]
with open ('test.in') as m:
        test=m.readlines()
        for i in range(8,len(test)):
            single_line=test[i].split('\t')
            mass.appened(float(single_line[0]))
            spectrum.append(float(single_line[1]))

假设我不想打开文件来检查从 intro 语句到第一行数据点的行数。如何让 python 自动从第一行数据点开始,并遍历文件的末尾?

标签: pythonpython-3.x

解决方案


spectrum=[]
mass=[]
with open ('test.in') as m:
    test=m.readlines()

    for line in test:
        if line[0] == '#':
            continue
        single_line=line.split('\t')
        mass.append(float(single_line[0]))
        spectrum.append(float(single_line[1]))

推荐阅读