Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first record from csv file using DictReader

Tags:

python

csv

I am trying to get the first record as a dict from a csv file using the DictReader. I am unable to understand as the documentation only talk about iterating the reader object

 with open(filename, 'r') as f_in:
        # Use the csv library to set up a DictReader object.
        trip_reader = csv.DictReader(f_in)
        # Use a function on the DictReader object to read the
        # first trip from the data file and store it in a variable.
        for row in trip_reader:
                   pprint(row)

Is there any function to get the first record as trip_reader[0]?

like image 673
wandermonk Avatar asked Jan 03 '23 01:01

wandermonk


2 Answers

Since you can iterate over trip_reader, you can call next() on it to get the next (in this case, the first row):

with open(filename, 'r') as f_in:
    # Use the csv library to set up a DictReader object.
    trip_reader = csv.DictReader(f_in)
    # Use a function on the DictReader object to read the
    # first trip from the data file and store it in a variable.
    row = next(trip_reader)
    pprint(row)
like image 96
Hai Vu Avatar answered Jan 05 '23 16:01

Hai Vu


To get first row of a CSV without a for loop:

with open(filename, 'r', newline='') as f:
    r = csv.reader(f, delimiter=',')
    return next(r)

Of course if you have a row of headers you'll have to "jump" over it:

with open(filename, 'r', newline='') as f:
    r = csv.reader(f, delimiter=',')
    _ = next(r) # hold header row in throwaway variable
    return next(r)

The newline='' in the context manager is used in Python3+ (maybe later versions of Python2 as well) but for Python2.7.8 and earlier you can omit.

like image 35
pstatix Avatar answered Jan 05 '23 16:01

pstatix