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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With