1

I need to grab the first row of a .csv file (the headers), and return it as a list.

I tried something like this:

import csv
with open('some.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row

But it prints the entire csv file. I was also thinking of just breaking the for loop immediately after printing the first row, but I didn't think that was the most efficient way to do it.

Is there a better way?

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114

1 Answers1

1

Since csv.reader object upports the iterator protocol you can simply call the next function on it to get the first item :

reader = csv.reader(f)
print next(reader)
Mazdak
  • 105,000
  • 18
  • 159
  • 188