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

前端 未结 7 757
误落风尘
误落风尘 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:38

    I am aware it is an old question, but I came up with a different answer than the ones presented. The reader object already increments the line_num attribute as you iterate through it. Then I get the total number of lines at first using row_count, then I compare it with the line_num.

    import csv
    
    def row_count(filename):
        with open(filename) as in_file:
            return sum(1 for _ in in_file)
    
    in_filename = 'somefile.csv'
    reader = csv.reader(open(in_filename), delimiter='|')
    
    last_line_number = row_count(in_filename)
    for row in reader:
        if last_line_number == reader.line_num:
            print "It is the last line: %s" % row
    

提交回复
热议问题