mewtire mewtire - 1 year ago 82
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:


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

Answer Source

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
        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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download