Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: StopIteration exception and list comprehensions

I'd like to read at most 20 lines from a csv file:

rows = [csvreader.next() for i in range(20)]

Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise.

Is there an elegant way to deal with an iterator that could throw a StopIteration exception in a list comprehension or should I use a regular for loop?

like image 463
Parand Avatar asked Jul 09 '09 23:07

Parand


1 Answers

You can use itertools.islice. It is the iterator version of list slicing. If the iterator has less than 20 elements, it will return all elements.

import itertools
rows = list(itertools.islice(csvreader, 20))
like image 198
Ayman Hourieh Avatar answered Nov 18 '22 13:11

Ayman Hourieh