在读取Python文件时跳过行块

2024-04-27 23:32:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由曲线数据组成的文件,其结构如下:

numbersofsamples
Title
     data
     data
     data
      ...

例如:

^{pr2}$

该文件由许多曲线组成,最高可达2GB。在

我的任务是通过跳过对我不感兴趣的块(曲线)来查找和导出特定的曲线。我知道曲线的长度(样本数),所以应该有一种方法跳转到下一个分隔符(例如numberofsamples),直到找到我需要的标题?在

我试图使用迭代器来实现这一点,不幸的是没有成功。这是完成任务的正确方法吗?在

如果可能的话,我不想把数据保存到内存中。在


Tags: 文件数据方法内存标题datatitle结构
2条回答

你不需要把所有的行都保存在内存中。跳到想要的标题,然后只保存留置权,您需要:

with open('somefile.txt') as lines
    # skip to title
    for line in lines
        if line == 'title youwant':
            break
    numbers = []
    for line in lines:
        if 'numberofsamples' in line:
            break # next samples
        numbers.append(line)

这是一种跳过你不关心的行的一般方法:

for line in file:
    if 'somepattern' not in line:
        continue
    # if we got here, 'somepattern' is in the line, so process it

相关问题 更多 >