2015-01-30 5 views
1

CSV 파일의 마지막 행을 어떻게 감지합니까? 그것은 반복자입니다하지만 난 마지막 행 감지 할 수있는 방법 찾을 수 없습니다 :파이썬에서 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

왜 마지막 행을 알아야합니까? 너는 그걸로 특별하게 뭐하고 있니? –

+0

은색 총알은'.next()'또는'.line_number' 일 수 있습니다. –

+0

@GamesBrainiac 나는'.next()'를 확인했다. @ 데인이 답변을 확인하십시오 http://stackoverflow.com/a/11479202/2029818 – michalczukm

답변

0

사용자 정의 동작을 할 때, 사용자 정의 iterater 쓰기입니다. 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 볼의.

0

당신은 언제나 목록으로 변환 언급

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

reader = csv.DictReader(csvfile, fieldnames) 

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

전체 파일을 메모리로 읽어 들이기 때문에 파일 크기가 클 경우 문제가 발생할 수 있습니다. –

+0

나는 상황의 요구에 가장 적합한 솔루션을 사용자가 정의 할 수 있도록 동의하지 않습니다. – Greg

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 
관련 문제