victorlin
victorlin

Reputation: 704

Python csv reader.next() vs next(reader)

When reading files using the csv module, there are two ways to iterate through the generator returned by csv.reader.

with open('foo.csv') as f:
    reader = csv.reader(f)
    row1 = reader.next()
    row2 = next(reader)

Is there any difference between how row1 and row2 are obtained? Is one preferred over the other?

Upvotes: 3

Views: 10162

Answers (1)

Alicia Garcia-Raboso
Alicia Garcia-Raboso

Reputation: 13913

In the beginning, the only option was to call iterator.next() on an iterator iterator. Python 2.6 introduced the builtin next(iterator), which simply called iterator.next() under the hood. In Python 3, next(iterator) calls iterator.__next__(), and iterator.next() raises an AttributeError. So unless you are on a really old version of Python (in which case you should upgrade anyway), use the builtin.

Upvotes: 3

Related Questions