How to loop through specific range of rows with Python csv reader?

前端 未结 3 1695
花落未央
花落未央 2021-01-18 00:15

How to loop through a specific range of rows with Python csv reader?

The following code loops through all rows:

with open(trainFile, \'rt\') as csvfi         


        
3条回答
  •  暖寄归人
    2021-01-18 00:50

    Another itertools implementation using dropwhile and takewhile

    from itertools import takewhile, dropwhile
    trainFile = 'x.1'
    low_lim = 3
    high_lim = 6
    with open(trainFile, 'rt') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        g = (x for x in enumerate(spamreader, 1))
        g = dropwhile(lambda x: x[0] < low_lim, g)
        g = takewhile(lambda x: x[0] <= high_lim, g)
        for row in g:
            print (', '.join(row[1]))
    

提交回复
热议问题