When you want custom behavior, write a custom iterater. Adapting the second example from this answer:
Empty = object()
class BooleanIterator(object):
"""
True/False tests: True means there are items still remaining to be used
"""
def __init__(self, iterator):
self._iter = iter(iterator)
self._get_next_value()
def __next__(self):
value = self._next_value
self._get_next_value()
if value is not Empty:
return value
raise StopIteration
next = __next__ # python 2.x
def __bool__(self):
return self._next_value is not Empty
__nonzero__ = __bool__ # python 2.x
def _get_next_value(self):
self._next_value = next(self._iter, Empty)
In your code:
csvfile = open('file.csv', 'r')
reader = BooleanIterator(csv.DictReader(csvfile, fieldnames))
for idx, row in enumerate(reader, start=1):
if reader:
# not the last row
# process normally
else:
# this is the last row!
For more examples of iterators see this answer.