繁体   English   中英

python csv reader,从第二行循环

[英]python csv reader, loop from the second row

在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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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