Python 中 csv reader 的最后一个元素

Last element of csv reader in Python

如何检测 csv 文件中的最后一行?它是一个迭代器,但我找不到检测最后一行的方法:

csvfile = open('file.csv', 'r')

reader = csv.DictReader(csvfile, fieldnames)

for idx, row in enumerate(reader, start=1):
    # How to detect last row?

您始终可以只转换为列表并获取列表的最后一个元素

csvfile = open('file.csv', 'r')

reader = csv.DictReader(csvfile, fieldnames)

all_lines = list(reader)
last_line = all_lines[-1]

如上所述,使用 next() 可能是最好的选择

csvfile     = open('file.csv', 'r')

reader = csv.DictReader(csvfile, fieldnames)

mycsv = enumerate(reader, start=1)
idx, row = mycsv.next()
while row:
    try:
       next_set = mycsv.next()
       pass # process set of (idx, row) here
       idx, row = next_set
    except StopIteration:
       pass # process last row here
       idx, row = None # make sure to unset to kill the loop

当你想要自定义行为时,写一个自定义迭代器。改编 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)

在您的代码中:

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!

有关迭代器的更多示例,请参阅 this answer