Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading column names alone in a csv file

Tags:

python

I have a csv file with the following columns:

id,name,age,sex

Followed by a lot of values for the above columns. I am trying to read the column names alone and put them inside a list.

I am using Dictreader and this gives out the correct details:

with open('details.csv') as csvfile:     i=["name","age","sex"]     re=csv.DictReader(csvfile)     for row in re:         for x in i:             print row[x] 

But what I want to do is, I need the list of columns, ("i" in the above case)to be automatically parsed with the input csv than hardcoding them inside a list.

with open('details.csv') as csvfile:         rows=iter(csv.reader(csvfile)).next()     header=rows[1:]     re=csv.DictReader(csvfile)     for row in re:         print row         for x in header:                          print row[x] 

This gives out an error

Keyerrror:'name' 

in the line print row[x]. Where am I going wrong? Is it possible to fetch the column names using Dictreader?

like image 264
Tania Avatar asked Mar 03 '15 16:03

Tania


People also ask

How do you read a column name while reading a CSV file?

While reading the CSV file, you can rename the column headers by using the names parameter. The names parameter takes the list of names of the column header. To avoid the old header being inferred as a row for the data frame, you can provide the header parameter which will override the old header names with new names.


1 Answers

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']) 
like image 157
user3194712 Avatar answered Oct 13 '22 18:10

user3194712