【问题标题】:Read multiple block of file between start and stop flags在开始和停止标志之间读取多个文件块
【发布时间】:2015-07-19 23:32:49
【问题描述】:

我正在尝试将文件的各个部分读入 numpy 数组,这些数组对于文件的不同部分具有相似的开始和停止标志。目前我找到了一种可行的方法,但在需要重新打开输入文件之前,只有输入文件的一部分。

我现在的代码是:

    with open("myFile.txt") as f:
        array = []
        parsing = False
        for line in f:
            if line.startswith('stop flag'):
            parsing = False
        if parsing:
            #do things to the data
        if line.startswith('start flag'):
            parsing = True

我从这个question找到了代码

使用此代码,我需要重新打开并阅读文件。

有没有一种方法可以读取所有部分,而不必为每个要读取的部分打开文件?

【问题讨论】:

  • 你的文件有多大/你对生成器有多满意?

标签: python


【解决方案1】:

你可以使用itertools.takewhile每次到达开始标志采取直到停止:

from itertools import takewhile
with open("myFile.txt") as f:
        array = []
        for line in f:
            if line.startswith('start flag'):               
                data = takewhile(lambda x: not x.startswith("stop flag"),f)
                # use data and repeat

或者只使用内部循环:

with open("myFile.txt") as f:
    array = []
    for line in f:
        if line.startswith('start flag'):
            # beginning of section use first lin
            for line in f:
                # check for end of section breaking if we find the stop lone
                if line.startswith("stop flag"):
                    break
                 # else process lines from section

一个文件对象返回它自己的迭代器,所以当你迭代f时指针会继续移动,当你到达开始标志时,开始处理一个部分,直到你到达停止点。根本没有理由重新打开文件,只需在文件的各行上迭代一次时使用这些部分。如果开始和停止标志线被认为是该部分的一部分,请确保也使用它们。

【讨论】:

    【解决方案2】:

    你有缩进问题,你的代码应该是这样的:

    with open("myFile.txt") as f:
        array = []
        parsing = False
        for line in f:
            if line.startswith('stop flag'):
            parsing = False
            if parsing:
            #do things to the data
            if line.startswith('start flag'):
            parsing = True
    

    【讨论】:

      【解决方案3】:

      与您类似的解决方案是:

      result = []
      parse = False
      with open("myFile.txt") as f:
          for line in f:
              if line.startswith('stop flag'):
                  parse = False
              elif line.startswith('start flag'):
                  parse = True
              elif parse:
                  result.append(line)
              else:  # not needed, but I like to always add else clause
                  continue
      print result
      

      但您也可以使用内部循环或itertools.takewhile,正如其他答案所建议的那样。特别是对于非常大的文件,使用 takewhile 应该会明显更快。

      【讨论】:

        【解决方案4】:

        假设这是您要阅读的文件:

        **starting** blabla blabla **starting** bleble bleble **starting** bumbum bumbum

        这是程序的代码:

        file = open("testfile.txt", "r")
        data = file.read()
        file.close
        data = data.split("**starting**")
        print(data)
        

        这是输出:

        ['', '\nblabla\nblabla\n', '\nbleble\nbleble\n', '\nbumbum\nbumbum']

        以后你可以del清空元素,或者在你的data中做其他操作。 split 函数是为 string 对象构建的,可以获取更复杂的字符串作为参数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-12-12
          • 1970-01-01
          • 2023-03-10
          • 1970-01-01
          • 1970-01-01
          • 2015-06-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多