0

I am having a problem reading specific lines. It's similar to the question answered here: python - Read file from and to specific lines of text The difference, I don't have a fixed end mark. Let me show an example:

--------------------------------
\n
***** SOMETHING *****     # i use this as my start
\n
--------------------------------
\n
data of interest
data of interest
data of interest
\n
----------------------- #this will either be dashes, or EOF
***** SOMETHING *****
-----------------------

I tried doing something similar to the above link, but I can't create a if statement to break the loop since I don't know if it will be the EOF or not.

Community
  • 1
  • 1
user1443368
  • 121
  • 1
  • 3
  • 9

3 Answers3

0

How about this:

def getBlocks(filepath):
    with open(filepath) as f:
        blocks = []
        go = False
        for line in f:
            if line.strip() == startDelimiter:
                block = ''
                go = True
            if go:
                block += line
            if line.strip() == endDelimiter:
                blocks.append(block)
                block = ''
                go = False
        if block:
            blocks.append(block)
    return blocks
inspectorG4dget
  • 104,525
  • 25
  • 135
  • 234
0

The beauty is that if you hit EOF, the file will stop iterating.

ended = False
for line in f:
    ended = line == MY_END_MARKER
Ali Afshar
  • 39,783
  • 12
  • 90
  • 108
0

Couldn't you just do

parts = my_file.read().split("-----------------------")
print parts
bluish
  • 24,718
  • 26
  • 114
  • 174
Joran Beasley
  • 103,130
  • 11
  • 146
  • 174