[Tutor] Parsing text file

Alan Gauld alan.gauld at btinternet.com
Mon May 14 01:10:26 CEST 2007

"Alan" <python at wardroper.org> wrote

> I'm looking for a more elegant way to parse sections of text files 
> that
> are bordered by BEGIN/END delimiting phrases, like this:
> some text
> someline1
> someline3
> more text
> What I have been doing is clumsy, involving converting to a string 
> and
> slicing out the required section using split('DELIMITER'):

The method I usually use is only slightly less clunky - or maybe
just as clunky!

I iterate over the lines setting a flag at the start and unsetting
it at the end. Pseudo code:

amInterested = False
for line in textfile:
    if amInterested and not isEndPattern(line):
    amInterested = not isEndPattern(line)
    if line.find(begin_pattern):
       amInterested = True

Whether thats any better than joining/splitting is debateable.
(Obviously you need to write the isEndPattern helper
function too)

Alan G. 

More information about the Tutor mailing list