There must be a better way
Tim Chase
python.list at tim.thechases.com
Sat Apr 20 20:34:22 EDT 2013
On 2013-04-21 00:06, Steven D'Aprano wrote:
> On Sat, 20 Apr 2013 19:46:07 -0400, Colin J. Williams wrote:
>
> > Below is part of a script which shows the changes made to permit
> > the script to run on either Python 2.7 or Python 3.2.
> >
> > I was surprised to see that the CSV next method is no longer
> > available.
>
> This makes no sense. What's "the CSV next method"? Are you talking
> about the csv module? It has no "next method".
In 2.x, the csv.reader() class (and csv.DictReader() class) offered
a .next() method that is absent in 3.x For those who use(d) the
csv.reader object on a regular basis, this was a pretty common
usage. Particularly if you had to do your own header parsing:
f = open(...)
r = csv.reader(f)
try:
headers = r.next()
header_map = analyze(headers)
for row in r:
foo = row[header_map["FOO COLUMN"]]
process(foo)
finally:
f.close()
(I did this for a number of cases where the client couldn't
consistently send column-headers in a consistent
capitalization/spaces, so my header-making function had to normalize
the case/spaces and then reference the normalized names)
> So provided you are using Python 2.6 or better, you call:
>
> next(inData)
>
> to get the next value, regardless of whether it is Python 2.x or
> 3.x.
>
> If you need to support older versions, you can do this:
>
> try:
> next # Does the built-in already exist?
> except NameError:
> # No, we define our own.
> def next(iterator):
> return iterator.next()
>
> then just use next(inData) as normal.
This is a good expansion of Chris Rebert's suggestion to use next(),
as those of us that have to support pre-2.6 code lack the next()
function out of the box.
-tkc
More information about the Python-list
mailing list