[Tutor] manipulating data

Alan Gauld alan.gauld at btinternet.com
Mon Nov 12 09:59:41 CET 2007


"Bryan Fodness" <bryan.fodness at gmail.com> wrote in

> fields = {}
> for line in open('data.txt') :
>    if line :   ## You shouldn't need this.
>       if line.split()[0] == 'field' :
>           field = int(line.split()[-1])
>       else :
>           fields[field] = tuple(line.split())
>
> fields[field] = tuple(line.split())
> NameError: name 'field' is not defined

As you should expect since you only define field inside
the if branch so if you go down the else route first then
field will not exist.

I'm jumping into this rather late but I'd have thought
something like this (untested code) might work:

fields = {}
for line in open('data.txt'):
    try:
       name,value = line.split()
       fields[name] = int(value)
    except AttributeError: pass  # catches blank lines

Or if you can control the data format the ConfigParser module
might be a better solution.


HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld






On Nov 8, 2007 7:34 AM, Ricardo Aráoz <ricaraoz at gmail.com> wrote:
>
> Kent Johnson wrote:
> > Bryan Fodness wrote:
> >> I would like to have my data in a format so that I can create a 
> >> contour plot.
> >>
> >> My data is in a file with a format, where there may be multiple 
> >> fields
> >>
> >> field = 1
> >>
> >> 1a   0
> >
> > If your data is really this regular, it is pretty easy to parse. A
> > useful technique is to access a file's next method directly. 
> > Something
> > like this (not tested!):
> >
> > f = open('data.txt')
> > fields = {} # build a dict of fields
> > try:
> >    while True:
> >      # Get the field line
> >      line = f.next()
> >      field = int(line.split()[-1]) # last part of the line as an 
> > int
> >
> >      f.next() # skip blank line
> >
> >      data = {} # for each field, map (row, col) to value
> >      for i in range(20): # read 20 data lines
> >        line = f.next()
> >        ix, value = f.split()
> >        row = int(ix[:-1])
> >        col = ix[-1]
> >        data[row, col] = int(value)
> >
> >      fields[field] = data
> >
> >      f.next()
> > except StopIteration:
> >    pass
> >
>
> Or maybe just (untested) :
>
> fields = {} # build a dict of fields
> for line in open('data.txt') :
>    if line :    # skip blank lines
>        if line.split()[0] == 'field' :
>            field = int(line.split()[-1])
>        else :
>            fields[field] = tuple(line.split())
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list