mewtire mewtire - 1 month ago 11
Python Question

Operating on a file with a very specific format

Mornin’ guys,

My friends and I have been trying to write the following function:

def track(filepath,n1,n2)


This function is meant to operate on a file with the following format:

-BORDER-
text
-BORDER-
text
-BORDER-
text
-BORDER-


how do i tell the function to operate on this file path and more precisely on the text inside each border?

Answer

Write a generator, that counts detect border lines and use groupby to separate these blocks:

from itertools import groupby

BORDER = '--border--'

def count_border(lines, border):
  cnt = 0
  for line in lines:
    if line.strip() == border:
        cnt += 1
    else:
        yield cnt, line

with open('file') as lines:
    for _, block in groupby(count_border(lines, BORDER), lambda (c,_): c):
        block = [line for _, line in block]
        print(block)