python csv reader,从第二行循环

时间:2013-05-03 02:00:15

标签: python

在python 2.7.3中,如何从第二行开始循环? e.g。

first_row = cvsreader.next();
for row in ???: #expect to begin the loop from second row
    blah...blah...

3 个答案:

答案 0 :(得分:14)

first_row = next(csvreader)  # Compatible with Python 3.x (also 2.7)
for row in csvreader:  # begins with second row
    # ...

测试确实有效:

>>> import csv
>>> csvreader = csv.reader(['first,second', '2,a', '3,b'])
>>> header = next(csvreader)
>>> for line in csvreader:
    print line
['2', 'a']
['3', 'b']

答案 1 :(得分:3)

next(reader, None) # Don't raise exception if no line exists

看起来最具可读性的IMO

另一种选择是

from itertools import islice
for row in islice(reader, 1, None)

但是你不应该使用标题吗?考虑csv.DictReader,默认情况下将字段名设置为第一行。

答案 2 :(得分:0)

假设第一行包含字段名称:

os