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?
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.
Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With