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? Kindly help. Thanks and regards.
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:
In the above, d_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...
If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:
I am just mentioning how to get all the column names from a csv file. I am using pandas library.
First we read the file.
Then, in order to just get all the column names as a list from input file use:-
here is the code to print only the headers or columns of the csv file.
Another method with pandas
How about
with open(csv_input_path + file, 'r') as ft: header = ft.readline() # read only first line; returns string header_list = header.split(',')
# returns list;I am assuming your input file is CSV format. If using pandas, it takes more time if the file is big size because it loads the entire data as the dataset.
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.Now i has the column's names as a list.
Also note that
reader.next()
does not work in python 3. Instead use the the inbuiltnext()
to get the first line of the csv immediately after reading like so:The
csv.DictReader
object exposes an attribute calledfieldnames
, and that is what you'd use. Here's example code, followed by input and corresponding output:Input file contents:
Output of print statements: