在 python 2.7.3 中,如何从第二行开始循环?例如
first_row = cvsreader.next();
for row in ???: #expect to begin the loop from second row
blah...blah...
在 python 2.7.3 中,如何从第二行开始循环?例如
first_row = cvsreader.next();
for row in ???: #expect to begin the loop from second row
blah...blah...
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']
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
默认情况下将字段名设置为第一行。
假设第一行包含字段名称:
import csv
for field in csv.DictReader(open("./lists/SP500.csv", 'rb')):
symbol = (field['ticker']).rstrip()