如何使用Python csv阅读器遍历特定的行范围?

时间:2013-09-26 14:45:03

标签: python csv

如何使用Python csv reader遍历特定范围的行?

以下代码遍历所有行:

with open(trainFile, 'rt') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        print (', '.join(row))

我希望仅从给定(i到j)循环。

3 个答案:

答案 0 :(得分:9)

您可以使用itertools.islice

import itertools

i, j = 10, 20
with open(trainFile, 'rt') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in itertools.islice(spamreader, i, j+1):
        print (', '.join(row))

替代方案(以下代码是可能的,因为csv.reader接受可迭代):

注意:仅当CSV行不包含换行符时才有效。

import itertools

i, j = 10, 20
with open(trainFile, 'rt') as csvfile:
    spamreader = csv.reader(itertools.islice(csvfile, i, j+1),
                            delimiter=' ', quotechar='|')
    for row in spamreader:
        print (', '.join(row))

答案 1 :(得分:2)

使用islice,例如:

rows_1_to_50 = itertools.islice(spamreader, 0, 50)
for row in rows_1_to_50:
    pass

答案 2 :(得分:1)

使用dropwhiletakewhile

的另一个itertools实现
from itertools import takewhile, dropwhile
trainFile = 'x.1'
low_lim = 3
high_lim = 6
with open(trainFile, 'rt') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    g = (x for x in enumerate(spamreader, 1))
    g = dropwhile(lambda x: x[0] < low_lim, g)
    g = takewhile(lambda x: x[0] <= high_lim, g)
    for row in g:
        print (', '.join(row[1]))