Python 3.2 在 csv.DictReader 中跳过一行
使用 DictReader 时如何跳过 CSV 中的一行记录?
代码:
import csv
reader = csv.DictReader(open('test2.csv'))
# Skip first line
reader.next()
for row in reader:
print(row)
错误:
Traceback (most recent call last):
File "learn.py", line 3, in <module>
reader.next()
AttributeError: 'DictReader' object has no attribute 'next'
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
next(reader)
来代替。来源: csv.DictReader 文档
You use
next(reader)
instead.Source: csv.DictReader documentation
从 Python 2.6 开始,您应该使用 next(foo) 而不是 foo.next()。
Since Python 2.6 you should use next(foo) instead of foo.next().
在 python2 中,将方法称为
next()
而不是__next__()
被认为是一个错误next(obj)
现在调用obj.__next__()
就像str
、len
等一样。您通常不会直接调用 obj.__next__(),就像您想要对象的字符串表示形式时不会直接调用 obj.__str__() 一样。
方便了解您是否发现自己编写了不寻常的迭代器
It was considered a mistake in python2 to have the method called
next()
instead of__next__()
next(obj)
now callsobj.__next__()
just likestr
,len
etc. as it should.You usually wouldn't call
obj.__next__()
directly just as you wouldn't callobj.__str__()
directly if you wanted the string representation of an object.Handy to know if you find yourself writing unusual iterators