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]?
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With