3
    self.viewerData = []
    tempViewerData = []
    tempViewer = []
    started = False
    with open("tittardata.txt", "r") as fp:
        for i, line in enumerate(fp.readlines()):
            if line.startswith("=="):
                started = True
                continue
            if started and line.startswith("--"):
                started = False
            if started == True:
                tempViewerData.append(line.rstrip("\n"))

I am trying to read the blocks from the txt file below which are separated by "---" on both ends. On the first block the separation is handled by different symbols starting with "===" and ending with "--". The upcoming blocks are parsed by the same symbol, making it more difficult to extract the blocks. This is my attempt this far, all help is appreciated.

Here is an extract from the text file:

=================
19.37/2
19.52/2
21.07/1
21.22/1
21.37/1
-------
19.37/2
19.52/2
-------
KMan
  • 31
  • 1
  • 2

2 Answers2

0
blocks = []
block = []

for line in f:
    if line[:3] in ('===', '---'):
        # don't record empty blocks, avoids empty block at start
        if block:
            blocks.append(block)
            block = []
    else:
        block.append(line.rstrip('\n'))
# needed if last block is not bounded by separator
if block:
    blocks.append(block)
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
0

Use a generator that effectively makes lines consisting only of = or - blank, then group by data that isn't blank, eg:

from itertools import groupby

with open('your_file') as fin:
    lines = (line.strip('-=\n') for line in fin)
    blocks = [list(g) for k, g in groupby(lines, bool) if k]
    # [['19.37/2', '19.52/2', '21.07/1', '21.22/1', '21.37/1'], ['19.37/2', '19.52/2']]

If you don't need the data all at once, then make blocks a generator instead and loop over that....

blocks = (list(g) for k, g in groupby(lines, bool) if k)
for block in blocks:
    # do something
Jon Clements
  • 138,671
  • 33
  • 247
  • 280