[Tutor] Reading text until a certain point

Alan Gauld alan.gauld at btinternet.com
Sat Jul 25 00:11:42 CEST 2009


"Stefan Lesicnik" <stefan at lsd.co.za> wrote

> I have a file that has text in a certain format. Lets assume
>
> '''
> name: stefan
> id: 12345
> color: blue
> name: joe
> id: 54321
> color: red
> '''
>
> The format is predictable.  I understand for non predictable text, you 
> would
> have to use pyparser or the like to build a match.

There are lots of ways to do this, I might use a class which takes
an open file and reads the three lines and extracts the data as
part of the contructor... Untested pseudo code:

class Item(object):
    def __init__(self, aFile):
        data = aFile.readline().strip().split(:)
        setattr(self, data[0], data[1])

items = []
f = open('myfile.txt')
while f:
     items.append(Item(f))


This of course breaks my own rule about not having objects for data only
but the intelligent constructor makes it worth it. :-)

Also there might well be other things you want to do to these elements
having collected them...

> The problem being i dont really do something per line?  I would like to 
> say
> something like, for line until the next 'name', make that 1 element.
> So i would like to then have a list or dict (this probably makes sense 
> for a
> dict) with that group. I would then probably split it into various 
> elements.

Just one alternative...


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list