简体   繁体   中英

Python 3.2 skip a line in csv.DictReader

How do I skip a line of records in a CSV when using a DictReader?

Code:

import csv
reader = csv.DictReader(open('test2.csv'))
# Skip first line
reader.next()
for row in reader:
    print(row)

Error:

Traceback (most recent call last):
  File "learn.py", line 3, in <module>
    reader.next()
AttributeError: 'DictReader' object has no attribute 'next'

You use next(reader) instead.

Source: csv.DictReader documentation

从Python 2.6开始,你应该使用next(foo)而不是foo.next()。

It was considered a mistake in python2 to have the method called next() instead of __next__()

next(obj) now calls obj.__next__() just like str , len etc. as it should.

You usually wouldn't call obj.__next__() directly just as you wouldn't call obj.__str__() directly if you wanted the string representation of an object.

Handy to know if you find yourself writing unusual iterators

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM