Best way to access the Nth line of csv file

You can use enumerate to iterate through the list until you find the right row:

for i, row in enumerate(reader):
    if i == line_number:
        print("This is the line.")
        print(row)
        break

You can also use itertools.islice which is designed for this type of scenario – accessing a particular slice of an iterable without reading the whole thing into memory. It should be a bit more efficient than looping through the unwanted rows.

def get_csv_line(path, line_number):
    with open(path) as f:
        return next(itertools.islice(csv.reader(f), line_number, None))

But if your CSV file is small, just read the entire thing into a list, which you can then access with an index in the normal way. This also has the advantage that you can access several different rows in random order without having to reset the csv reader.

with open(path) as f:
    my_csv_data = list(csv.reader(f))
print(my_csv_data[line_number])

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)