[Tutor] Reading text until a certain point

vince spicer vinces1979 at gmail.com
Fri Jul 24 17:51:30 CEST 2009


you can build a dictionary and keep the active key, again this would only
work in predictable data

users = {}
name = None

for line in file:
    key, value = [x.strip() for x in line.split(":")]
    if key == "name":
        name = data[1]
        users[name] = {}
     else:
         users[name][data[0]]

>> users
{"stefan": {
          "id":12345
          "color":blue
})

Vince

On Fri, Jul 24, 2009 at 9:39 AM, Stefan Lesicnik <stefan at lsd.co.za> wrote:

> Hi Guys,
>
> It seems like this keeps coming up (for me anyways), and i'm never sure how
> to do it. I'm very new to programming...
>
> 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.
>
> For predictable format, I am never sure how to handle this. I normally use
> something like
>
> for line in file:
>     line.split('\n')
>
> 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.
>
> So essentially im asking, how do i say the for line until next 'match'.
> Would this be something for the re module? Or is there an inbuilt core way?
>
> I hope this makes sense
>
> Thanks!
>
> Stefan
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090724/eb6807c8/attachment.htm>


More information about the Tutor mailing list