How to loop through a specific range of rows with Python csv reader?
The following code loops through all rows:
with open(trainFile, \'rt\') as csvfi
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))
Alternative (following code is possible because csv.reader accept an iterable):
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))