Best way to access the Nth line of csv file

后端 未结 6 1212
陌清茗
陌清茗 2020-12-13 13:56

I have to access the Nth line in a CSV file.

Here\'s what I did:

import csv

the_file = open(\'path\', \'r\')
reader = csv.reader(the_file)

N = inpu         


        
6条回答
  •  猫巷女王i
    2020-12-13 14:00

    You could minimize your for loop into a comprehension expression, e.g.

    row = [row for i,row in enumerate(reader) if i == N][0]  
    
    # or even nicer as seen in iCodez code with next and generator expression
    
    row = next(row for i,row in enumerate(reader) if i == N)
    

提交回复
热议问题