How to create a list using the first line of CSV file in python

advertisements

I'm trying to create a list out of the first row - the column headers - of a csv file using python. I put together this little script, but it prints two different lists. The first item printed is the first row of the csv and the second thing printed in the second row.

What am I doing wrong?

import csv
import sys

with open('agentsFullOutput.csv') as csvFile:
    reader = csv.reader(csvFile)
    print csvFile.next()
    field_names_list = []
    field_names_list = csvFile.next()
    print field_names_list


Every time you call .next() it'll move on to the next row in the file. So you'll only get the headers of the CSV file in the first .next() call:

import csv

with open('agentsFullOutput.csv') as csvFile:
    reader = csv.reader(csvFile)
    field_names_list = reader.next()

Any subsequent .next() call will read the next row in the file so that would be a row of data.