8

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

以下代码循环遍历所有行:

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

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

4

3 回答 3

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))
于 2013-09-26T14:50:04.990 回答
2

使用islice,例如:

rows_1_to_50 = itertools.islice(spamreader, 0, 50)
for row in rows_1_to_50:
    pass
于 2013-09-26T14:49:55.297 回答
1

dropwhile另一个使用and 的itertools 实现takewhile

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]))
于 2013-09-26T14:54:48.860 回答