如何检测csv文件中的最后一行?它是一个迭代器,但我找不到检测最后一行的方法:
csvfile = open('file.csv', 'r')
reader = csv.DictReader(csvfile, fieldnames)
for idx, row in enumerate(reader, start=1):
# How to detect last row?
答案 0 :(得分:2)
如前所述,使用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
答案 1 :(得分:0)
您始终只需转换为列表并获取列表的最后一个元素
csvfile = open('file.csv', 'r')
reader = csv.DictReader(csvfile, fieldnames)
all_lines = list(reader)
last_line = all_lines[-1]
答案 2 :(得分:0)
如果需要自定义行为,请编写自定义迭代器。调整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。