Have csv.reader tell when it is on the last line

前端 未结 7 756
误落风尘
误落风尘 2021-01-05 00:43

Apparently some csv output implementation somewhere truncates field separators from the right on the last row and only the last row in the file when the fields are null.

7条回答
  •  无人及你
    2021-01-05 01:40

    Basically you only know you've run out after you've run out. So you could wrap the reader iterator, e.g. as follows:

    def isLast(itr):
      old = itr.next()
      for new in itr:
        yield False, old
        old = new
      yield True, old
    

    and change your code to:

    for line_num, (is_last, row) in enumerate(isLast(reader)):
        if not is_last: assert len(row) == len(header)
    

    etc.

提交回复
热议问题