Read multiple block of file between start and stop flags

前端 未结 4 1182
轮回少年
轮回少年 2020-12-06 23:53

I am trying to read sections of a file into numpy arrays that have similar start and stop flags for the different sections of the file. At the moment I have found a method

4条回答
  •  甜味超标
    2020-12-07 00:49

    The solution similar to yours would be:

    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
    

    But you might also use inner loop or itertools.takewhile as other answers suggest. Especially using takewhile should be significantly faster for really big files.

提交回复
热议问题