Reading by positions plain text files
Javier Van Dam
javivd319 at hotmail.com
Wed Dec 1 07:40:38 EST 2010
Ok. I will try it and let you know. Thanks a lot!!
J
> Date: Tue, 30 Nov 2010 20:32:56 -0600
> From: python.list at tim.thechases.com
> To: javiervandam at gmail.com
> CC: python-list at python.org
> Subject: Re: Reading by positions plain text files
>
> On 11/30/2010 08:03 PM, javivd wrote:
> > On Nov 30, 11:43 pm, Tim Harig<user... at ilthio.net> wrote:
> >>> VARIABLE NAME POSITION (COLUMN) IN FILE
> >>> var_name_1 123-123
> >>> var_name_2 124-125
> >>> var_name_3 126-126
> >>> ..
> >>> ..
> >>> var_name_N 512-513 (last positions)
> >>
> > and no, MRAB, it's not the similar problem (at least what i understood
> > of it). I have to associate the position this file give me with the
> > variable name this file give me for those positions.
>
> MRAB may be referring to my reply in that thread where you can do
> something like
>
> OFFSETS = 'offsets.txt'
> offsets = {}
> f = file(OFFSETS)
> f.next() # throw away the headers
> for row in f:
> varname, rest = row.split()[:2]
> # sanity check
> if varname in offsets:
> print "[%s] in %s twice?!" % (varname, OFFSETS)
> if '-' not in rest: continue
> start, stop = map(int, rest.split('-'))
> offsets[varname] = slice(start, stop+1) # 0-based offsets
> #offsets[varname] = slice(start+1, stop+2) # 1-based offsets
> f.close()
>
> def do_something_with(data):
> # your real code goes here
> print data['var_name_2']
>
> for row in file('data.txt'):
> data = dict((name, row[offsets[name]]) for name in offsets)
> do_something_with(data)
>
> There's additional robustness-checks I'd include if your
> offsets-file isn't controlled by you (people send me daft data).
>
> -tkc
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101201/6f837180/attachment-0001.html>
More information about the Python-list
mailing list