如何使用Python csv reader遍历特定范围的行?
以下代码遍历所有行:
with open(trainFile, 'rt') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print (', '.join(row))
我希望仅从给定(i到j)循环。
答案 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)
使用dropwhile
和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]))