How to create list using first row of CSV file in python

13,257

Solution 1

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.

Solution 2

Each time you call next() the next line from the file is yielded until the end of the file is reached.

In your code example, since you call next() twice, and in the second call you assign it to field_name_list, it assigns the 2nd row, not the first.

The following will assign the first row to the variable field_names_list.

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

Using next(reader) instead of reader.next() means that the code is portable to Python 3. On the 3+ series, the iterator's next() method has been renamed to __next__() for consistency.

Share:
13,257
DBWeinstein
Author by

DBWeinstein

Co-Founder at HomeKeepr. Coding hobbyist. Always learning about everything.

Updated on June 14, 2022

Comments

  • DBWeinstein
    DBWeinstein almost 2 years

    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
    
  • Haleemur Ali
    Haleemur Ali about 9 years
    csvFile.next() will read the line as a string and assign to field_names_list. perhaps you meant reader.next() or csvFile.next().strip('\n').split(',')
  • Simeon Visser
    Simeon Visser about 9 years
    @HaleemurAli: actually yes, I meant reader.next() - thanks, I have updated the answer.
  • DBWeinstein
    DBWeinstein about 9 years
    @SimeonVisser Thanks! The only issue i'm having now is the list comprised of each individual character. I've tried using the excel dialect, but it's not working. reader = csv.reader(csvFile, dialect='excel').
  • Nikki_Champ
    Nikki_Champ almost 9 years
    I have tried the same with my CSV file which has about 16 elements seperated by ';' but Python is reading it as a single string in the list.... I mean the length of the list is 1 instead of 16. But from the second line it is considered as 16. I dont know why this is happening. Any help??