如何使用Python csv reader循环访问特定范围的行? [英] How to loop through specific range of rows with Python csv reader?
本文介绍了如何使用Python csv reader循环访问特定范围的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Python csv reader循环访问特定范围的行?
How to loop through a specific range of rows with Python csv reader?
以下代码遍历所有行:
with open(trainFile, 'rt') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print (', '.join(row))
我希望只从给定的(i到j)循环。
I wish to loop only from given (i to j).
推荐答案
//docs.python.org/2/library/itertools.html#itertools.islicerel =nofollow> itertools.islice
:
You can use 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行不包含换行符。
NOTE: only works when CSV rows do not contain newline.
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))
这篇关于如何使用Python csv reader循环访问特定范围的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文