[Tutor] mapping header row to data rows in file

Sivaram Neelakantan nsivaram.net at gmail.com
Thu Jun 27 05:19:53 CEST 2013


On Wed, Jun 26 2013,Peter Otten wrote:


[snipped 36 lines]

> from collections import namedtuple
>
> def reader(instream):
>     rows = (line.split() for line in instream)
>     names = next(rows)
>     Row = namedtuple("Row", names)
>     return (Row(*values) for values in rows)
>
> with open(FILENAME, "r") as f:
>     for row in reader(f):
>         print row.name
>
I get these errors with the code above

Row = namedtuple("Row", names)
File "/usr/lib/python2.7/collections.py", line 278, in namedtuple
raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
ValueError: Type names and field names can only contain alphanumeric characters and underscores: 'Symbol,Series,Date,Prev_Close'



--8<---------------cut here---------------start------------->8---

Symbol,Series,Date,Prev_Close
STER,EQ,22-Nov-2012,         9
STER,EQ,29-Nov-2012,        10
STER,EQ,06-Dec-2012,        11
STER,EQ,06-Jun-2013,         9
STER,EQ,07-Jun-2013,         9

def reader(instream):
    rows = (line.split() for line in instream)
    names = next(rows)
    Row = namedtuple("Row", names)
    return (Row(*values) for values in rows)

with open("AA.csv", "r") as f:
    for row in reader(f):
        print row.name

--8<---------------cut here---------------end--------------->8---

 sivaram
 -- 



More information about the Tutor mailing list