Best way to access the Nth line of csv file

后端 未结 6 1213
陌清茗
陌清茗 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条回答
  •  一个人的身影
    2020-12-13 14:04

    Your solution is actually not that bad. Advancing the file iterator to the line you want is a good approach and is used in many situations like this.

    If you want it more concise though, you can use next and enumerate with a generator expression:

    import csv
    
    the_file = open('path', 'r')
    reader = csv.reader(the_file)
    
    N = int(input('What line do you need? > '))
    
    line = next((x for i, x in enumerate(reader) if i == N), None)
    print(line)
    
    the_file.close()
    

    The None in there is what will be returned if the line is not found (N is too large). You can pick any other value though.


    You could also open the file with a with-statement to have it be automatically closed:

    import csv
    
    with open('path', 'r') as the_file:
        reader = csv.reader(the_file)
    
        N = int(input('What line do you need? > '))
    
        line = next((x for i, x in enumerate(reader) if i == N), None)
        print(line)
    

    If you really want to cut down on size, you could do:

    from csv import reader
    N = int(input('What line do you need? > '))
    with open('path') as f:
        print(next((x for i, x in enumerate(reader(f)) if i == N), None))
    

提交回复
热议问题