Reading column names alone in a csv file

You can read the header by using the next() function which return the next row of the reader’s iterable object as a list. then you can add the content of the file to a list.

import csv
with open("C:/path/to/.filecsv", "rb") as f:
    reader = csv.reader(f)
    i = reader.next()
    rest = list(reader)

Now i has the column's names as a list.

print i
>>>['id', 'name', 'age', 'sex']

Also note that reader.next() does not work in python 3. Instead use the the inbuilt next() to get the first line of the csv immediately after reading like so:

import csv
with open("C:/path/to/.filecsv", "rb") as f:
    reader = csv.reader(f)
    i = next(reader)

    print(i)
    >>>['id', 'name', 'age', 'sex']

Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-

  • Python's DictReader object in the CSV module (as of Python 2.6 and above) has a public attribute called fieldnames. https://docs.python.org/3.4/library/csv.html#csv.csvreader.fieldnames

An implementation could be as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    d_reader = csv.DictReader(f)

    #get fieldnames from DictReader object and store in list
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])

In the above, d_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...

>>> print(headers)
['MyCol1', 'MyCol2', 'MyCol3']

If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    #you can eat the first line before creating DictReader.
    #if no "fieldnames" param is passed into
    #DictReader object upon creation, DictReader
    #will read the upper-most line as the headers
    f.readline()

    d_reader = csv.DictReader(f)
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])

Tags:

Python