13

在 python 2.7.3 中,如何从第二行开始循环?例如

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

3 回答 3

23
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']
于 2013-05-03T02:05:16.880 回答
4
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默认情况下将字段名设置为第一行。

于 2013-05-03T02:35:58.660 回答
0

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

import csv
for field in csv.DictReader(open("./lists/SP500.csv", 'rb')):
    symbol = (field['ticker']).rstrip()
于 2017-03-07T19:15:10.087 回答