[英]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.